poke
poke

Reputation: 387667

C++ int & long marshalling in C#

I'm currently porting a proprietary dll (an API) to C#, and I have some problems when marshalling some of the used data types.

For example the API header file defines the following types:

typedef unsigned int  tINT;  /* natural unsigned */
typedef signed int    tINTs; /* natural signed */
typedef unsigned int  tLONG; /* 32 bit unsigned */
typedef unsigned long tPTR;  /* 32/64-bit pointer */

Then I for example have the following function definition:

tINTs SomeApiFunction ( const tPTR hdl, tINT param );

I'm usually marshalling the int directly with C#'s int (Int32), or the unsigned version. The API's tLONG and tINT are as such the same (at least for the API). But I'm not sure with the tPTR. I have now made it a uint in C#, because it is a 32bit int, but I'm not sure how the long would behave on a 64bit machine.

What do I have to do to make sure that the API will work on both 32bit and 64bit machines correctly?

This is what I would have done now:

[DllImport( "api.dll" )]
public static extern int SomeApiFunction ( uint hdl, uint param );

Sadly the API is not really well documented, as such I am not sure what the intention was with all those (overlapping) typedefs. Apart from the header comments I have included above there is no information about the actual types.

Upvotes: 3

Views: 9203

Answers (4)

Mikael Svenson
Mikael Svenson

Reputation: 39695

Try to Marshal it as an IntPtr. IntPtr is 4 bytes on a 32bit system and 8 bytes on a 64bit system in .Net.

Upvotes: 3

Liviu Mandras
Liviu Mandras

Reputation: 6617

Here is good list of type correspondence.

For pointer types is usually IntPtr in C#.

Upvotes: 2

Hans Passant
Hans Passant

Reputation: 941465

It is an implementation detail of the C/C++ compiler. You should go by the comment and declare it IntPtr. If the code is compiled by the MSVC compiler then it isn't going to work in 64-bit mode, it uses 32-bits for a long. Not enough to store a pointer.

Upvotes: 3

langerra.com
langerra.com

Reputation: 777

If I remember correctly int uint and other primitive types are the right type for the underlying windows API.

For pointers however, its best to use IntPtr on C# side and void* on C/C++ side.

Upvotes: 1

Related Questions