C # calls a method for C DLLs with struct pointers

Source: Internet
Author: User

Tag: Port error--Modify point C + + imp call struct

in the In C # when invoking C (c + +) class DLL, sometimes C's interface function contains a lot of parameters, and some times these parameters may be a struct, and possibly a struct pointer, then in C # How to safely call such a DLL interface function? This article describes in detail how to invoke various parameters in a method.

First,The calling interface contains only ordinary variables
int fnadd (int num1,int num2);

so in C # calls this function the simplest, directly with the function prototype, as follows:

[DllImport (" your DLL name ""fnadd", callingconvention =  CALLINGCONVENTION.CDECL)]publicstaticexternint fnadd (int int num2);

this in This DLL function can be used with confidence in C # methods.

Second,a pointer to a calling interface with a normal variable

we all know that. C # for the sake of security, invisible to avoid the pointer (in fact, in C # can use pointers, just for the sake of security), the use of reference to replace the pointer, the advantage of reference is that the pointer can manipulate the parameters of the original address of the data, and the data when the call function returned to survive, But the reference can not think of the pointer like + + or--to this PC pointer running around, a series of problems, the following example to manipulate the normal variable pointer, as follows:

int fnadd (int *p_n1,int *p_n2);

It's already been said. C # uses references instead of pointers, so it's good to say that the calling interface can write:

[DllImport (" your DLL name ""fnadd", callingconvention =  CALLINGCONVENTION.CDECL)]publicstaticexternint fnadd (ref int num1,refint num2);

Yes, it's just that simple, so C # can invoke a normal variable with pointers.

Third,Call the interface with the structure of a slightly more difficult point

in the The header file of C contains such a simple struct

struct mybuf{    int  num1;     int num2;}

The interface functions are as follows:

int fnadd (struct mybuf mydata);

so this is How does C # invoke such an interface function? First in C # We want to declare a struct, in the C # struct is not discarded, but in the use of the structure to pay attention to some details, such as to call C DLL so it is best to add some modifiers to the struct defined within C # , as follows:

[StructLayout (layoutkind.sequential)] Public structmybuf{ Public intNUM1;  Public intnum2;  PublicMybuf (intN1,intn2) {NUM1=N1; Num2=N2; }}[dllimport ("the name of your DLL", EntryPoint ="Fnadd", CallingConvention =callingconvention.cdecl)] Public Static extern intFnadd (Mybuf MyData);

you might find out how this structure looks like a class, yes. The struct in C # is really a special class, and there are constructors, such as the public mybuf (int n1,int n2) in the example above.

we may also see the definition of struct before we use StructLayout such a struct layout modifier, which

is actually very useful, we used the LayoutKind.Sequential This property, which is especially useful when the parameters of a DLL are pointers, because your structure in C is in sequential layout, so we also use the sequential layout in C #, so that when the pointer is passed within the C DLL there will be no error (not necessarily).

In addition, you see the member variables of the struct we all use the public modifier, when there is no public only a statement such as int num1, C # default member variable is protected, then you in C # Other methods within the definition of this struct can not be arbitrarily accessed to modify its member variables (only through the constructor new when initialized), so you need to use public to decorate the member variables.

Four,continue to some difficulty, in fact, there is no difficulty, isDLL interface parameters contain struct-body pointers
NT Fnadd (struct mybuf *p_mydata), or write int fnadd (void *p_mydata)

the above two functions are actually the same, because c specifies that a pointer of type void can point to any data type, except that it is mandatory for your data type within the C function entity, such as:

struct mybuf*p = (structmybuf*) p_mydata;

so in How do you call this function interface in C #? Very simple extrapolate ref ...

okay , here's the code:

[StructLayout (layoutkind.sequential)] Public structmybuf{ Public intNUM1;  Public intnum2;  PublicMybuf (intN1,intn2) {NUM1=N1; Num2=N2; }}[dllimport ("the name of your DLL", EntryPoint ="Fnadd", CallingConvention =callingconvention.cdecl)] Public Static extern intFnadd (refMybuf MyData);

yes, that's It's OK.

Five,In fact, there are more complex calls, such as nested structures inside structures, nested struct pointers, and structures containing arrays, all of which need to beC#

In the declaration of the structure of the time required special treatment, temporarily do not increase the difficulty.

in order to continue to increase the difficulty, the following continue to add several situations, to rise up a bit posture ...

Six,The struct within the DLL interface parameter contains a shape, a character array

Below the structure of the body

struct mybuf{    int  A;     int b;     BOOL bl;     int arr[];     Char ch[[];};

DLL inside the interface prototype is an int fnadd (struct mybuf mydata), then how can this be called under C #?

in the The layout of the data in C # differs greatly from the layout of the data in C (c + +), so when users need to pass data between C # and C code, they must manually tell C # 's boss. NET how this batch of data is passed to C's DLL for use; so this involves C # Legacy issues ( data marshaling ). not much to say the first code, in C # How to declare such a struct, as follows:

[StructLayout (layoutkind.sequential)] Public structmybuf{ Public intNUM1;  Public intnum2;  Public BOOLFLG; //shaping an array[MarshalAs (UnmanagedType.ByValArray, SizeConst = $)]     Public int[] buf; //character Array[MarshalAs (unmanagedtype.byvaltstr, SizeConst = -)]     Public Char[] ch;  PublicMybuf (intN1,intN2,BOOLBL) {NUM1=N1; Num2=N2; FLG=BL; BUF=New int[ $]; CH=New Char[ -]; }};

Yes, you may be surprised to find the declaration of each value before adding a [Marshalasxxxx] field, what is this for? This is the data marshaling format for the previous red font labels, a brief introduction, The MarshalAs property tells the. Net how to marshal the following data into the DLL interface, and when the value of UnmanagedType is ByValArray, it tells the following data to be an array, and that the ByValArray value must be followed by SizeConst to tell. NE t the size of this array, as above; in fact, when you write code in the VS2010, when you press "." After entering UnmanagedType, the VS will automatically pop-up box will list a lot of data marshaling format, each format has Chinese ToolTip to explain, see for yourself will understand The previous time saw the character array and the shaping data data marshaling format is not the same, the shaping uses the ByValArray, but the character uses the ByValTStr, but actually I measured down when the character uses the ByValTStr to debug when the return error, said illegal marshaling format, The character is also changed to ByValArray after the OK, do not know what the problem? and continue to study. Then continue, in C # to encapsulate the structure, you can call directly, whether it is a struct or struct pointer in accordance with the previous method can be used.

C # calls a method for C DLLs with struct pointers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.