Reputation: 81
The function in dll has the prototype below
void Foo(int arg1, int& arg2);
The question is, how to declare the function prototype in C?
Is the declaration legal?
void Foo(int, int*);
Upvotes: 5
Views: 224
Reputation:
You need an adapter, consisting of a C++ translation unit and a header usable from both C and C++, like this (use better names of course):
adapter.h:
#ifndef ADAPTER_H
#define ADAPTER_H
#endif
#ifdef __cplusplus
extern "C" {
#endif
void adapter_Foo(int arg1, int *arg2);
// more wrapped functions
#ifdef __cplusplus
}
#endif
#endif
adapter.cpp:
#include "adapter.h"
// includes for your C++ library here
void adapter_Foo(int arg1, int *arg2)
{
// call your C++ function, e.g.
Foo(arg1, *arg2);
}
You can compile this adapter into a separate DLL or you can have it as a part of your main program. In your C code, just #include "adapter.h"
and call adapter_Foo()
instead of Foo()
.
Upvotes: 5
Reputation: 170044
Is the declaration legal?
It is, but it doesn't declare the same function. If you need a C API, you cannot use a reference. Stick to a pointer, and make sure the function has C linkage:
extern "C" void Foo(int, int*) {
// Function body
}
If you cannot modify the DLL code, you need to write a C++ wrapper for it that exposes a proper C API.
Upvotes: 8