Reputation: 1
I know this has already been discussed but after 3days I haven't figured out why I keep getting a blank string after calling a C function wrapped in a DLL in C# :
[DllImport(DllName, CharSet = CharSet.Ansi)]
public static extern int QA_FormatExample(int viHandle, int viExample [MarshalAs(UnmanagedType.LPStr)]StringBuilder rsComment)
In Main :
StringBuilder rsComment = new StringBuilder(256);
apiWrap.QA_FormatExample(currentInstance, viExample, rsComment);
System.Diagnostics.Debug.WriteLine(rsComment);
Function's signature :
int __stdcall QA_FormatExample(int, int, char*);
The function QA_FormatExample
initializes rsComment
once called but I keep getting rsComment
blank. Any suggestion would be really appreciated, thank you.
Upvotes: 0
Views: 1760
Reputation: 612844
In order to match the C++ the function should be declared like this:
[DllImport(DllName)]
public static extern int QA_FormatExample(
int viHandle,
int viExample,
StringBuilder rsComment
);
And you call it like this:
StringBuilder comment = new StringBuilder(256);
int res = QA_FormatExample(handle, example, comment);
Which is very close to what you present in the question. So, if your calls to the function do not work, then your problems lie in the code that we cannot see. What I show above is the correct way to marshal text from native to managed via char*
.
I would point out that it is a little unusual that you do not pass the length of buffer to the function. Without that information, the maximum length must be hardcoded.
Upvotes: 1