cooldj
cooldj

Reputation: 43

How to import void ** C++ API into C#?

In c++ API Declaration is

BOOL DCAMAPI dcam_attachbuffer          ( HDCAM h, void** top, _DWORD size );

arguments : void** top--- is the array of pointer to buffer _DWORD size-- is size of top parameter in bytes

In c#, this is how I import the dll file:

[DllImport("dcamapi.dll", EntryPoint = "dcam_attachbuffer",
          CallingConvention = CallingConvention.StdCall,
          CharSet = CharSet.Ansi, BestFitMapping = false,
          ThrowOnUnmappableChar = true)]
        [return: MarshalAsAttribute(UnmanagedType.Bool)]

   public static extern bool dcam_attachbuffer(IntPtr handleCamera,
 [MarshalAsAttribute(UnmanagedType.LPArray)]ref Int32[] buf, 
[MarshalAsAttribute(UnmanagedType.U4)] Int32 bufsize);

My question is do I convert the type from c++ into c# correctly? and How do I declare void**in c#? please help me.

Upvotes: 3

Views: 1398

Answers (3)

vpp
vpp

Reputation: 317

It is depending on what function dcam_attachbuffer do.

If it's taking buffer, define method

[DllImport("dcamapi.dll", EntryPoint = "dcam_attachbuffer"]
public static extern bool dcam_attachbuffer(
    IntPtr handleCamera,
    IntPtr ptrsBuf, 
    Int32 bufSize);

and pass pointer derived earlier.

If function is getting pointer of pointers, define method

[DllImport("dcamapi.dll", EntryPoint = "dcam_attachbuffer"]
public static extern bool dcam_attachbuffer(
    IntPtr handleCamera,
    ref IntPtr ptrsBuf, 
    Int32 bufSize);

and use

System.Runtime.InteropServices.Marshal.Copy(
    IntPtr source,
    IntPtr[] destination,
    int startIndex,
    int length
)

to copy pointers in IntPtr[]

Upvotes: 2

Hans Passant
Hans Passant

Reputation: 941705

The argument is IntPtr[] (no ref). With the unnecessary attributes removed:

[DllImport("dcamapi.dll")]
public static extern bool dcam_attachbuffer(IntPtr handleCamera, 
    IntPtr[] buf, int bufsize);

Correctly initializing the array could be a challenge as well, it is quite unclear from the question what is required.

Upvotes: 2

You can declare pointers directly in C# in unsafe blocks.

There's also IntPtr.

Or you can write some C++/CLI to glue the two together.

Upvotes: 2

Related Questions