在c#中使用dll的问题

时间:2010-06-24 22:57:29

标签: c# com dll

我需要在c#程序中使用非托管COM dll。 Dll包含一个函数,比如说:

Open(char *name);

但是当导入到c#(项目 - >添加参考)时,它可用作:

mydll.Open(ref byte name)

如何将字符串传递给此函数?

当我这样做时:

byte[] name = new byte[32];
mydll.Open(ref name);

我收到编译错误“无法将ref byte []转换为ref字节”。

5 个答案:

答案 0 :(得分:1)

如果你的意思是它是一个字符串,那么在你的IDL文件中,你必须指定这个点代表一个字符串。有关[string]属性的信息,请参阅此文章: http://msdn.microsoft.com/en-us/library/d9a4wd1h%28v=VS.80%29.aspx 如果您希望符合CLS(并与脚本语言互操作,您可能希望使用BSTR而不是char *来传递字符串)。这样你也可以获得unicode支持。

除非你给COM提示这是一个字符串,否则每当COM必须编组参数时(即跨公寓或进程边界),你就会遇到问题。

本文也可以为您提供C ++ / C#/ COM好东西的良好起点: COM Interop Part 1: C# Client Tutorial

答案 1 :(得分:0)

也许你可以这样做......

byte [] bytes = Encoding.ASCII.GetBytes(myString);

答案 2 :(得分:0)

您可以尝试使用以下内容装饰“name”变量:

[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)]

这是一个单字节,我认为与单个字符串兼容。如果没有,答案可能是使用MarshalAs使变量看起来像类型。

答案 3 :(得分:0)

请记住,如果阵列未正确终止,您可能会丢失它。无论如何,我会尝试传入指向第一个元素byte [0]的指针:

mydll.Open(ref name [0]);

我不确定互操作会如何编组,但值得一试。

答案 4 :(得分:0)

导入不正确。您可以手动导入它:

[DllImport("<Your COM Dll>")]
private static extern <Return Type> <"Function Name">();

然后,在您的main方法或初始化dll对象的方法中,您需要:

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr LoadLibrary(string lpFileName);

public MyDll()
{
    Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    string dllPath = Environment.CurrentDirectory + @"<Location of Dll you are importing from>";
    LoadLibrary(dllPath);
}

例如,请查看以下COM Dll:

GOIO_DLL_INTERFACE_DECL gtype_int32 GoIO_GetNthAvailableDeviceName(
char *pBuf,         
gtype_int32 bufSize,
gtype_int32 vendorId,   
gtype_int32 productId,  
gtype_int32 N);

我将此Dll导入如下:

[DllImport("GoIO_DLL.dll")]
private static extern int GoIO_GetNthAvailableDeviceName(
byte[] pBuf, 
int bufSize, 
int vendorId,
int productId,
int N);

如您所见,char指针变为byte [],就像您尝试过的那样。不需要ref关键字。