this is my C code
extern "C"
{
__declspec(dllexport) void DisplayHelloFromDLL(string a)
{
printf ("%s\n",a)
}
}
this is my C# code
class HelloWorld
{
[DllImport("TestLib.dll")]
public static extern void DisplayHelloFromDLL(string a);
static void Main ()
{
string a = "Hello";
DisplayHelloFromDLL(a);
}
}
It built successfully but crash like this:
Debug http://i44.tinypic.com/1qr9sj.jpg
SO,how to use P/invoke to call my own C dll from C#? Please help,thanx in advance.
First of all your code is C++ rather than C. Your function receives a parameter of type
std::string
and the use ofstd::string
means that your code is actually C++.Now this parameter type is the root of your problem. You cannot create a
std::string
in .net and instead will need to use achar*
to pass the string data. The following code is what you need:C++
C#
The default p/invoke marshalling for a .net
string
is to pass achar*
as an[In]
parameter. There is no need for the complexity ofIntPtr
,StringToHGlobalAnsi
,FreeHGlobal
as suggested by one of the other answers. If you can let the p/invoke marshaller do the work then it is preferable to do so.Note that you also need to make sure that your calling conventions match. Under the assumption that you have not used any special compiler options when building your C++ code, that code will default to used
cdecl
calling convention. You can make that match with theCallingConvention
parameter to theDllImport
attribute.Change your C++ param type to char* and update your C# code as following
For one thing the return type is not matching. In C it is
void
and in C#int
.Please take a look at marshalling string at MSDN
In a nut shell, a C# string doesn't get marshalled as
std::string
but achar*
by default