views:

52

answers:

2

The following .net to native C code does not work, any ideas

extern "C" {
   TRADITIONALDLL_API int TestStrRef( __inout char* c)    {
   int rc = strlen(c);
   std::cout << "the input to TestStrRef is: >>" << c << "<<" ;
   c = "This is from the C code ";
   return rc;
   }
 }

 [DllImport("MyDll.dll", SetLastError = true)]
 static extern int TestStrRef([MarshalAs(UnmanagedType.LPStr)] ref string s);
 String abc = "InOut string";
 TestStrRef(ref abc);

At this point Console.WriteLine(abc) should print "This is from the C code " but doesn't, Any ideas on what's wrong ?

FYI - i have another test function not using ref type string, it works just fine

A: 

Does this work for you? Basically just add CallingConvention = CallingConvention.Cdecl to the DllImport statement. You might also want to specify the CharSet (for example: CharSet:=CharSet.Unicode)

 [DllImport("MyDll.dll", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
 static extern int TestStrRef([MarshalAs(UnmanagedType.LPStr)] ref string s);
SwDevMan81
Why would the calling convention matter? Calling the method(s) is already working for the OP.
Henk Holterman
Anyways i tried, it didn't work!
Kumar
+4  A: 

Your code wrong at C side also. __inout annotation just tell compiler you can change buffer to which "c" argument pointed. But pointer itself located in stack and does not return to caller if you modified "c" argument. Your declaration may look like:

extern "C" {
   TRADITIONALDLL_API int TestStrRef( __inout char** c)    {
   int rc = strlen(*c);
   std::cout << "the input to TestStrRef is: >>" << *c << "<<" ;
   *c = "This is from the C code ";
   return rc;
   }
 }

And C# side:

[DllImport("MyDll.dll", SetLastError = true)]
static extern int TestStrRef(ref IntPtr c);

{
    String abc = "InOut string";
    IntPtr ptrOrig = Marshal.StringToHGlobalAnsi(abc)        
    IntPtr ptr = ptrOrig; // Because IntPtr is structure, ptr contains copy of ptrOrig
    int len = TestStrRef(ref ptr);
    Marshal.FreeHGlobal(ptrOrig); // You need to free memory located to abc' native copy
    string newAbc = Marshal.PtrToStringAnsi(ptr); 
    // You cannot free memory pointed by ptr, because it pointed to literal string located in dll code.
}
Tarhan
+1, this is correct. Not being able to release the memory is of course a serious problem, it only doesn't cause a leak here by accident. Using strcpy() instead is a great way to destroy the heap.
Hans Passant
There is no need for the "ref" in the IntPtr, and the code could be better, but it is right! +1!
Ricardo Nolde