Question about interop / C++

  • Thread starter Thread starter Stefan Slapeta
  • Start date Start date
S

Stefan Slapeta

Hi all,


I've no idea how to write the C# signatures for these four kinds of
parameters of C++ (better: C) functions exported from a DLL:

// i is ONLY out
void f1(unsigned int *i);

// ai is ONLY out and terminated by 0:
void f2(unsigned int ai[]);

// ai is ONLY in:
void f3(unsigned int ai[]);

// asz is an array of const char* and ONLY in
void f4(const char **asz);


Maybe one of you could help me!

Thanks,

Stefan
 
Stefan,

This is how you would write them:

[DllImport("my.dll")]
public static extern void f1(out uint i);

[DllImport("my.dll")]
public static extern void f2(IntPtr ai);

[DllImport("my.dll")]
public static extern void f3(uint[] ai);

[DllImport("my.dll", CharSet=CharSet.Ansi)]
public static extern void f3(String[] ai);

f1 and f3 should be fairly obvious. f2 requires an IntPtr because in C,
passing ai is the same as passing a pointer to an unsigned int. This
indicates to me that you are pre-allocating the memory for ai before you
pass the pointer in. If f2 was allocating the array, you would have a
pointer to the array, which is a double indirection, which is not indicated
here. You need the IntPtr because marshaling doesn't know how to marshal
C-style arrays from the unmanaged to the managed realm, so you have to do it
manually.

f4 is also obvious as well, I believe. The only note here is that you
terminate your string array correctly.

Hope this helps.
 
Hi Nicholas,

first, thanks for your help!
[DllImport("my.dll")]
public static extern void f2(IntPtr ai);

[...]

f2 requires an IntPtr because in C,
passing ai is the same as passing a pointer to an unsigned int. This
indicates to me that you are pre-allocating the memory for ai before you
pass the pointer in.

Yes, you are absolutely right.
You need the IntPtr because marshaling doesn't know how to marshal
C-style arrays from the unmanaged to the managed realm, so you have to do it
manually.

Could you please give me a short example how to to that? I'm not really
experienced with this kind of things yet. How could I pass e.g. an
uint[5] to this function?


Thanks in advance,

Stefan
 
Stefan Slapeta wrote:

Could you please give me a short example how to to that? I'm not really
experienced with this kind of things yet. How could I pass e.g. an
uint[5] to this function?

Thanks - I've found it in the MSDN!

Stefan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top