从Windows的C函数返回一个字符串 [英] Returning strings from Windows C functions

查看:210
本文介绍了从Windows的C函数返回一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个完整的新手在C和C ++纯粹的Windows API级的功能和最近已尝试用.NET互操作能力。我已经建立已成功为.NET调用者返回数值(INT /浮动等),一个简单的库,但我不会有尽可能多的运气字符串。

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.

我已经尝试了多种不同的数据类型,但没有出现工作:LPSTR,LPCSTR,LPCTSTR和LPCWSTR。诚然,我没有尝试过的char *。另外,一旦方法被设置为返回一个字符串,它需要由.NET编组作为一个特定的数据类型,或可以被简单地直接读入以System.String对象?我曾尝试解析为一个IntPtr然后铸造成一个字符串,但没有成功。

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.

推荐答案

做什么的Windows API的一样。它通常不会返回指针,它填补了您传递的缓冲区。

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

管理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
); 

在C / C ++侧:

On the C/C++ side:

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

这篇关于从Windows的C函数返回一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆