[Mono-dev] Interop with Native Libraries Question

Jonathan Pryor jonpryor at vt.edu
Wed Mar 5 07:49:07 EST 2008


On Wed, 2008-03-05 at 12:09 +0200, Sebi Onofrei wrote:
> I have a library from which I have to use some methods which is
> written in C++.

First, make sure the C++ methods are declared `extern "C"`.

> The method I need to correctly translate is this:
> integer method_name(const void* a_handle, char* name, int* length)

Do you have the source code to `method_name' that you can provide?

What is the actual type of `integer'?

void* is usually an IntPtr.

Is `name' an input parameter or an output parameter?  If `name' is an
input parameter, it should be `string' in your P/Invoke.  If it's an
output parameter (e.g. the `dest' parameter in strcpy(3)), StringBuilder
should work.

Does `length' need to have a valid value before the call?  If it does,
`ref int' should be used, otherwise `out int'.

> Next I tried  this:
>         [DllImport (libraryName, EntryPoint = "method_name", CharSet =
> CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
>         private static unsafe extern integer EXT_method_name(void*
> handle, StringBuilder name, ref int length);
> this doesn't work either

In what way doesn't this work?  `integer' isn't a valid C# type (unless
it's a type of your own creation).

> Then I tried this:
>         [DllImport (libraryName, EntryPoint = "method_name", CharSet =
> CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
>         private static unsafe extern integer EXT_method_name(IntPtr
> handle, StringBuilder name, out int length);
> and this doesn't work either :(

Again, in what way does this fail?

Also keep in mind that the StringBuilder needs to have space allocated
*before* the method call; see:

  http://mono-project.com/Dllimport#Passing_Caller-Modifiable_Strings

> In mono's wiki there is an example with StringBuilder (the strncpy
> example), but either I did something wrong or some different approach
> is needed.

Alas, without seeing the caller-side code, it's difficult to say.  My
best guess is that you're not providing a Capacity to the StringBuilder
instance you provide.

It would also be helpful to know in what way the method is failing.

 - Jon




More information about the Mono-devel-list mailing list