从 Windows C 函数返回字符串

发布于 2024-10-08 20:34:44 字数 304 浏览 9 评论 0原文

我对 C 和 C++ 中的纯 Windows API 级函数完全是新手,最近一直在尝试 .NET 互操作性。我已经构建了一个简单的库,它已成功地将数值(int/float 等)返回给 .NET 调用者,但我在字符串方面没有那么幸运。

我尝试了各种不同的数据类型,但似乎都不起作用:LPSTR、LPCSTR、LPCTSTR 和 LPCWSTR。诚然,我还没有尝试过 char*。另外,一旦将方法设置为返回字符串,是否需要通过 .NET 将其编组为特定数据类型,或者是否可以直接将其读入 System.String 对象?我尝试解析为 IntPtr 然后转换为字符串,但这不起作用。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最偏执的依靠 2024-10-15 20:34:44

执行 Windows API 执行的操作。它通常不返回指针,而是填充您传入的缓冲区。

托管代码:

[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
); 

在 C/C++ 方面:

DWORD WINAPI SomeArbitraryFunction (
    LPCSTR input,
    LPSTR output,
    DWORD outputMaxLen
);

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
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文