Returning strings from Windows C functions

好久不见. 提交于 2019-12-23 01:36:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!