28 9月 2010

[Implement] How C# use native library from C code

Target platform: Visual C# 2010 Express
Source platform: Visual C++ 2005 Professional ( to generate the DLL file )


[Part A] : To create a native C library (.dll)
1. new project --> Win32 project ( Note: not MFC --> MFC DLL ) --> in the application setting page,
select the below properties: (type:DLL), (additional options:Export symbols)

2. in your header file of the project, define the export function like this:

( DLLRESPIRATION0927 is my project name.)


// my export method 
extern "C" DLLRESPIRATION0927_API int  __stdcall fnRespiration( int count,short buffer[] );
Note:
if you don't add the macro extern "C", Visual C# will appear the error message: "Unable to find  an entry point", when you call this method.
if you don't add the macro __stdcall, the C# program can't find this function.

About extern "C",
because the C++ has the overloading function, it won't be supported by C.
We use this macro to close the overloading mechanism in C++ compiler.

3. in the .cpp file, declare the function like this:

DLLRESPIRATION0927_API int __stdcall fnRespiration(int count,short buffer[])
{
    return 0;
}


4. in the .cpp file, you need to include the header files of the C code. ex:

extern "C"{
#include "..\\xxxLib_globals.h"
}
especially note the extern "C"{} macro, i think it tells the compiler the included file is C code, not the C++ file.


5. There is one thing you need to NOTE!!
Because we want to use native C code to generate the DLL and the platform we used is visual "C++", there will be a compile error like this:
fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?


Solution is to change the property of the used C code:
property--> Precompiled Header-->Create/Use Precompiled Header--> 
change the Default setting : Use Precompiled Header (/Yu)  to Not Using precompiled Headers   

Finally, build the project and got the .dll file.

[Part.B] : use the dll in your C# project.
1. Put the DLL file to the reference folder. 
For my example, I use the default executable path of application. ( ..\bin\Debug\ )
You can use the instruction to get:
System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath)
Note: If you put the file in the wrong place, the program will crash during the runtime.

2.Add those declaration codes in your class:

[DllImport("dllRespiration0927.dll")]
public static extern int fnRespiration(int count, short[] inputAr);

3. Then you should be able to use the method directly in your project. enjoy it :P

沒有留言:

張貼留言