4
Answers

How to pass referenced string from c dll to c#

Ridzuan

Ridzuan

14y
3.5k
1
I have problem to pass a referenced string to c#. Below are the code for c dll and c#

c dll code

extern "C" __declspec(dllexport) int test(string &msg)
{
    msg = "test";
    return 0;
}

c# code

[DllImport("c_dll.dll")]
public static extern int test(ref StringBuilder newMsg);

StringBuilder aaa = new StringBuilder();
aaa.append("");

int a = test(ref aaa);

i can compiled it successfully but whenever I tried to run it, I get this error
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Please help to indicate which part of the code is wrong. Thank you
Answers (4)
0
Ridzuan

Ridzuan

NA 5 0 14y
thanks.. it works.. thanks for the advice
0
theLizard

theLizard

NA 5.1k 282.2k 14y
extern "C" __declspec(dllexport) int test(string &msg)
{
    msg = "test";
    return 0;
}

you are attempting to get the string from c# by refereance [ &msg ] this is probably where you are having the problem since the error message tells you that
This is often an indication that other memory is corrupt. 

try sending the string using an (LPTSTR msg)  int a = test(aaa);  this should work as it does in C++ builder for me.

extern "C" __declspec(dllexport) int stdcall  test(LPTSTR msg)   //not sure if stdcall is valid for your situ
{
    msg = "test";
    return 0;
}

0
Ridzuan

Ridzuan

NA 5 0 14y
I've tried to use string but the result is same.
0
Jaish Mathews

Jaish Mathews

NA 7.3k 1.2m 14y
Can u replace "StringBuilder" with "string" and try?