0

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.

4
  • Does it definitely get set in the C code? Commented Jan 20, 2014 at 13:48
  • How is the C function exported? C defaults to cdecl calling convention, C# defaults to stdcall -- If you haven't specified __stdcall as the calling convention in the C function then you have to specify CallingConvention.Cdecl in the DllImport decoration. Commented Jan 20, 2014 at 13:51
  • Thank you both for your answers. Rughes - yes, the C code definitely set the 'rsComment', it's an API function of one of my company products so it has already been tested. J - the full signature for the C function is : __declspec(dllimport) int __stdcall QA_FormatExample(int, int, char *) , so it's already specified as a 'stdcall'. Commented Jan 20, 2014 at 14:00
  • @user3215290 - please add that to the question. Commented Jan 20, 2014 at 14:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.