tags:

views:

165

answers:

5

I need to use an unmanaged COM dll in c# program. Dll contains a function, say:

Open(char *name);

But when imported to c# (Project->Add Reference) it is available as:

mydll.Open(ref byte name)

How can I pass a string to this function?

When I do:

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

I get compilation error "Cannot convert ref byte[] to ref byte".

A: 

Maybe you can do this...

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

Steve Sheldon
A: 

You might try decorating that "name" variable with:

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

That's a single byte, and I think is compatibel with a single char. If not, the answer is likely going to be using MarshalAs to make that variable look like type.

Robert Seder
A: 

Keep in mind you could lose it if the array is not properly terminated. Anyhow, I would try passing in the pointer to the first element byte[0] try:

mydll.Open(ref name[0]);

I'm not sure how the interop will marshal this but it's worth a try.

ddm
A: 

If you mean for it to be a string, then in your IDL file, you have to specify that this point represents a string. See this article for information on the [string] attribute: http://msdn.microsoft.com/en-us/library/d9a4wd1h%28v=VS.80%29.aspx If you want to be CLS compliant (and interoperate with scripting languages, you might want to look into using BSTR instead of char* for passing strings). This way you'll get unicode support too.

Unless you give COM the hint that this is a string, you will have problems whenever COM has to marshal the parameters (i.e. across apartment or process boundaries).

This article may also give you a good starting point on C++ / C# / COM goodies: COM Interop Part 1: C# Client Tutorial

Garo Yeriazarian
A: 

The import is not correct. You can import it manually:

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

Then, in your main method, or in the method where you initialize your dll object, you need:

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

For example, check out the following COM Dll:

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

I imported this Dll as the following:

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

As you can see, the char pointer becomes a byte[], just like you tried. There is no need for the ref keyword.

sbenderli