I have a C lib and want to call function in this library from C# application. I tried creating a C++/CLI wrapper on the C lib by adding the C lib file as linker input and adding the source files as additional dependencies.
Is there any better way to achieve this as am not sure how to add C output to c# application.
My C Code –
__declspec(dllexport) unsigned long ConnectSession(unsigned long handle,
unsigned char * publicKey,
unsigned char publicKeyLen);
My CPP Wrapper –
long MyClass::ConnectSessionWrapper(unsigned long handle,
unsigned char * publicKey,
unsigned char publicKeyLen)
{
return ConnectSession(handle, publicKey, publicKeyLen);
}
The example will be, for Linux:
1) Create a
Cfile,libtest.cwith this content:That’s a simple pseudo-wrapper for printf. But represents any
Cfunction in the library you want to call. If you have aC++function don’t forget to put externCto avoid mangling the name.2) create the
C#file3) Unless you have the library libtest.so in a standard library path like “/usr/lib”, you are likely to see a System.DllNotFoundException, to fix this you can move your libtest.so to /usr/lib, or better yet, just add your CWD to the library path:
export LD_LIBRARY_PATH=pwdcredits from here
EDIT
For Windows, it’s not much different.
Taking an example from here, you only have yo enclose in your
*.cppfile your method withextern "C"Something like
then, compile, and in your C# file do
and then just use it: