2

I am a complete novice at pure Windows API-level functions in C and C++ and have been experimenting recently with .NET interoperability. I have built a simple library which has successfully returned numeric values (int/float, etc.) to a .NET caller, but I am not having as much luck with strings.

I have tried a variety of different data types, but none appear to work: LPSTR, LPCSTR, LPCTSTR, and LPCWSTR. Admittedly, I haven't tried char*. Also, once a method is set up to return a string, does it require marshalling by .NET as a specific data type, or could it be simply read straight into a System.String object? I have tried parsing into an IntPtr then casting into a string but that did not work.

2
  • 3
    Just for your reference, LPSTR and char * are the same type. If you look in the Windows SDK headers, you'll find typedef char * LPSTR;. Commented Dec 22, 2010 at 2:13
  • .NET works in UTF-16. It's better to use wchar_t* and avoid unnecessary character encoding conversion. Commented Dec 22, 2010 at 5:47

1 Answer 1

7

Do what the Windows API does. It typically does not return pointers, it fills in buffers that you pass in.

Managed code:

[DllImport("YourLibrary", CharSet = CharSet.Auto)] 
static extern Int32  SomeArbitraryFunction (
    String        input,          // string passed to API (LPCSTR) 
    StringBuilder output,         // output filled by API (LPSTR)    
    Int32         outputMaxLen    // StringBuilder.Capacity
); 

On the C/C++ side:

DWORD WINAPI SomeArbitraryFunction (
    LPCSTR input,
    LPSTR output,
    DWORD outputMaxLen
);
Sign up to request clarification or add additional context in comments.

4 Comments

Great advice. I suggest that you also provide an example of the C code that matches this p/invoke declaration.
I've given it a go, but I am still not getting any text out. How would I go about populating the LPSTR with text? Also, how would I join two pieces of text together?
Can you pass data in the other direction? (If you have the LPCSTR, does that receive something from managed code?) To populate the buffer pointed to by LPSTR you use an strcpy variant... preferably _strncpy_s.
Okay - got it working! My problem was populating the StringBuilder object, which I have now achieved!

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.