开发者

How to marshal pointer types when calling C dll function in C#

I need to call a c function imported from a dll. I can find how to import the api function but I am unsure how to marshal all the types the function expects as paramters. Particularly pointer types.

Example function signature might be...

Result_Type get_signal_value( SIG* sig, char* name, int *value );

where SIG is a sturcture containing various items. eg. struct SIG { char sig_id[16]; int sig_ptr; HW_ADDR_TYPE hw_info; };

and

struct HW_ADDRESS_TYPE { short channel_no; unsigned char chassis; unsigned char slot; unsigned char link; unsigned char filler; };

I can find that to Marshal this type I need to describe the structure layout...

[StructLayout(LayoutKind.Sequential)] public class HW_ADDRESS_TYPE { short channel_no; byte chass开发者_JAVA技巧is; byte slot; byte link; byte filler; } ;

[StructLayout(LayoutKind.Sequential)] public class SIG { public const int LEN_SID = 16; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = LEN_SID)] public string sig_id; int sig_ptr; HW_ADDRESS_TYPE hw_info; };

but seem to have problems here. have I done this correctly?

Same for the int* in the example.

Any help would be great. Cheers!


[StructLayout(LayoutKind.Sequential)]
struct SIG
{
    // describe the fields here
}

[DllImport("lib.dll")]
static extern bool get_signal_value(SIG sig, string name, float value);

Which you might call:

SIG sig = new SIG();
sig.Field1 = value1;
sig.Field2 = value2;
bool result = get_signal_value(sig, "abc", 1.5f);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜