Beacon80

Okay, I've got a rather complicated program going on in C++. Rather than try to convert it all to C#, I compiled it to a DLL and put a wrapper in it with functions to run the program and then extract the crucial bits of information. This is where the problem is. I need to return a character array, but the best I can do is get one letter back.

Here's my code:

C++:
__declspec(dllexport) void __stdcall GetString(char **outStr, int *outStrLen)
{
// Copy the needed string to outStr, its length to outStrLen
}

C#

[DllImport("MyDLL.dll")]
extern static void GetString(ref char[] outStr, ref int outStrLen);

I tried using the MarshallAs function, but then I get the following error:
Cannot use SizeParamIndex for ByRef array parameters.
I get this even if I don't use SizeParameterIndex. And if I remove "ref" I get this:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Any ideas


Re: Visual C# General Passing a string from a C++ DLL

eradicator

GetString accepts an already-allocated array, right If so, then it should just take a char*, not a char**. And then you don't need to pass outStr as a ref (because the method isn't setting outStr itself to point to some address, it is only setting the contents of the array).

__declspec(dllexport) void __stdcall GetString(char* outStr, int* outStrLen) ...

extern static void GetString(char[] outStr, ref int outStrLen) ...

Treat this as just a guess, but probably somewhat better than a random guess.






Re: Visual C# General Passing a string from a C++ DLL

Beacon80

Sadly, that doesn't work. I get complaints during runtime that something is trying to read or write protected data.




Re: Visual C# General Passing a string from a C++ DLL

Beacon80

Nevermind, I figured it out. The trick is to use StringBuilder.
More information can be found here.