简体   繁体   中英

Passing an Array to Pointer inside a Structure in C# application

I am having a unmanaged library . I want to create a C# application using the unmanaged library. I am using 'DllImport' to import the functions from the unmanaged library.

In C++ the structure and the function calling the structure looks as shown below

typedef struct _DATA_BUFFER {

UCHAR *buffer;                // variable length array      
UINT32 length;                 // lenght of the array     
UINT32 transferCount;               

} DATA_BUFFER,*P_DATA_BUFFER;

byte  Write (HANDLE handle, DATA_CONFIG *dataConfig, DATA_BUFFER *writeBuffer, UINT32 Timeout);        

In C# I defined the structure and function as shown below

[StructLayout(LayoutKind.Sequential, Pack = 1)] 

public unsafe struct DATA_BUFFER
{
public byte* buffer;
public UInt32 length;
public UInt32 transfercount;             
};

[DllImport("Library.dll")]

public unsafe static extern byte Write([In] IntPtr hHandle, DATA_CONFIG* dataConfig,   DATA_BUFFER* WriteBuffer, UInt32 timeout);


for (byte i = 0; i < length; i++)
transfer[i] = i;

DATA_BUFFER buffer_user = new DATA_BUFFER();
buffer_user.length = length;
buffer_user.buffer = transfer;

return_status = Write(handle , &dataconfig , &buffer_user , 1000);

I am getting error 'Cannot implicity convert type byte[] to byte .

I tried using fixed and other . Nothing is working .

How do I assign an array (In this case Tranfer[]) to the pointer (public byte* buffer ) in the structure . I need to pass it to above mentioned function?

Your struct DATA_BUFFER uses a byte* buffer. But I guess you understand the error.

Try

fixed (byte* b = transfer) buffer_user.buffer = b;

inside an unsafe context of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM