问题
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.
回答1:
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
);
来源:https://stackoverflow.com/questions/4505493/returning-strings-from-windows-c-functions