【发布时间】:2012-12-08 11:23:50
【问题描述】:
我在 Visual C++ 中有以下返回类型:
extern "C" __declspec(dllexport) unsigned char* _cdecl
getname(LPCTSTR Track1, int len)
我已经编写了以下代码以在 C# 中获取 unsigned char* 的正确值:
[DllImport(_dllLocation, CallingConvention = CallingConvention.Cdecl)]
public static extern byte[] getname(string track1, int len);
我使用以下代码从另一个 .cs 文件中调用了上述方法:
string track = "hello12345";
byte[] name = UnsafeNativeMethods.getname(track, 160);
请告诉我在这里做错了什么,还请检查参数数据类型,即LPCTSTR 和string。
unsigned char* 是否等同于 byte[]。如果是这样,那么为什么我在 C# 文件中得到错误的值,而在 C++ 中它是正确的。
编辑:
在通过 cmets 提出一些建议后,我已将 byte name 更改为 byte[] name,但它显示以下异常:
A first chance exception of type 'System.Runtime.InteropServices.MarshalDirectiveException' occurred in DecryptionWS.dll
A first chance exception of type 'System.Runtime.InteropServices.MarshalDirectiveException' occurred in DecryptionWS.dll
A first chance exception of type 'System.Runtime.InteropServices.MarshalDirectiveException' occurred in System.ServiceModel.dll
A first chance exception of type 'System.Runtime.InteropServices.MarshalDirectiveException' occurred in System.ServiceModel.dll
【问题讨论】:
-
您的
getnameextern 方法返回一个字节,但您像byte[]一样使用它。是字节还是字节[]? -
我的错,现在我编辑了它
-
我也试过了:
byte[] name = UnsafeNativeMethods.getname(track, 160);Console.Writeline (name);但它会停止程序并抛出System.InvalidOperationException' occurred in System.ServiceModel.Web.dll -
Console.WriteLine(name)只会打印System.Byte[]。你期待什么价值?如果您需要一个字符串,则需要使用System.Text.Encoding.UTF8.GetString(name)(或您使用的任何编码格式)。 -
@keyboardP 请看代码编辑部分
标签: c# visual-studio-2010 visual-c++ types bytearray