Code Optimization

Interesting things in software development and code optimization

C#.NET and unmanaged static C++ library

Hi friends,

Today I'm going to share my experience with c++ static libraries.


Static library differs from dynamic library by that, that parts of static library code will be included into caller code.

For example, I have an exe and my exe code calls a function from a static library. It means that this static library function's code will be included into my exe and I will not need any library to be with the exe.


But with C# such things are going to be more tricky, because of C#.NET is managed code and static library is unmanaged code and thus could not be linked and included.

So we need another way to do it. As you know we can use PInvoke to be able to access exported dll functions, and this is going to help us a lot.

First step is to create a Dll C++ project and link a static library to this Dll, our dll project is going to be something like a wrapper, and add some export method so we would be able to invoke them from C#.NET code.

Here is how to do it:

extern "C" __declspec(dllexport) int InitializeLib2(int type, const char *data, BOOL useFlag)

{

return ::InitializeLib(type, data, useFlag);

}

so we have declared our InitializeLib2 function for export and to be used via PInvoke from C# code, inside of this InitializeLib2 function we have a call to a static library InitializeLib function  and just pass parameters from our method.

Now we build it and get a Dll file that can be pinvoked from our C# code.

Here is how to do it:

[DllImport("MyWrapper.dll", CallingConvention = CallingConvention.Cdecl)]

public static extern int InitializeLib2(int zero, ref byte str, bool b);

and here how to call this method:

byte[] str = ASCIIEncoding.ASCII.GetBytes("my string data" + ((char)0).ToString());

int a = InitializeLib2(0, ref str[0], false);

so we pass an integer value, I like to pass strings as byte array and last parameter is boolean value.


Thats all. At the end of this you will have MyWrapper.dll and managed exe file.

Thank you, and good luck :)


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



Loading