Marshal structure pointer in VS2010 - c#

I have to call a C++ DLL from my C# program.
I'm trying to do it using PInvoke - everything works fine in VS2005\ 2008, but after migration to VS 2010, I get this exception:
PInvokeStackImbalance was detected
Message: A call to PInvoke function
'sampleFunc' has unbalanced the stack.
This is likely because the managed
PInvoke signature does not match the
unmanaged target signature. Check that
the calling convention and parameters
of the PInvoke signature match the
target unmanaged signature.
This is the original C++ prototype:
typedef struct {
unsigned short field1;
unsigned short field2;
} sInfo;
_declspec(dllexport) int sampleFunc(sInfo *info, char *txt);
and here is the C# code:
[StructLayout(LayoutKind.Sequential)]
struct SInfo
{
//[MarshalAs(UnmanagedType.U1)] //also tried with the MarshalAs attr. Didn't help.
public ushort field1;
//[MarshalAs(UnmanagedType.U1)]
public ushort field2;
};
[DllImport("sampleModule.dll", CharSet=CharSet.Ansi)]
public static extern int sampleFunc(ref SInfo info, [MarshalAs(UnmanagedType.LPStr)] string txt);
I've tried it also with IntPtr instead of the ref SInfo, but got the same result...
Any help will be appreciated,
Thank you all!

Hard to see how this could have worked before. The C++ declaration doesn't declare the calling convention, the default is __cdecl unless overridden in the C++ project with the /Gz compile option. You have to tell the P/Invoke marshaller:
[DllImport("sampleModule.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int sampleFunc(ref SInfo info, string txt);

This probably has to do with how your packing the struct. The default Pack size is 8, so its probably thinking you have too many bytes. Try setting the Pack size to 2 (16 bit aligned) and see if that helps:
[StructLayout(LayoutKind.Sequential, Pack=2)]
Alternatively you can specify the offsets like this:
[StructLayout(LayoutKind.Explicit)]
public struct struct1
{
[FieldOffset(0)]
public ushort a; // 2 bytes
[FieldOffset(2)]
public ushort b; // 2 bytes
}
Here is a good reference on packing

Related

C# DllImport - Call a function that returns an struct

I am working in C# and I need to call a function in a C++ dll library. This function returns a struct but I can´t get anything.
This is the function I need to call and the struct that returns in C++ library:
ATHENA_API _DEVICE_INFO* __stdcall GetDeviceInfoKeepConnection(_DEVICE_INFO* pDeviceInfo);
typedef struct TD_DEVICE_INFO{
TCHAR chDeviceName[256];
int nCommPort;
int nECGPos;
int nNumberOfChannel;
int nESUType;
int nTymestampType;
int nDeviceHandle;
TCHAR chDeviceID[260];
}_DEVICE_INFO;
This is my C# code trying to call the function:
[DllImport(#"\BAlertSDK\ABM_Athena.dll")]
static extern _DEVICE_INFO GetDeviceInfoKeepConnection(_DEVICE_INFO deviceInfo);
[StructLayout(LayoutKind.Sequential)]
struct _DEVICE_INFO
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string chDeviceName;
public int nCommPort;
public int nECGPos;
public int nNumberOfChannel;
public int nESUType;
public int nTymestampType;
public int nDeviceHandle;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string chDeviceID;
}
void Test_Click()
{
_DEVICE_INFO d = new _DEVICE_INFO();
_DEVICE_INFO deviceInfo = GetDeviceInfoKeepConnection(d);
}
The only I can get is an empty _DEVICE_INFO object. I think my problem is that I am not defining correctly the DEVICE INFO struct.
I have never worked with dll´s to this level. Can you help me?
Thanks in advance.
Thanks to all!! The problem has solved with this:
Parameter pass by reference and struct charset Unicode.
It seems that the function GetDeviceInfoKeepConnection returns a pointer to _DEVICE_INFO struct. So, in your C# code, you need to change the definition of the function to:
[DllImport(#"\BAlertSDK\ABM_Athena.dll")]
static extern IntPtr GetDeviceInfoKeepConnection(IntPtr deviceInfo);
And then you can access the struct data like this:
void Test_Click()
{
_DEVICE_INFO d = new _DEVICE_INFO();
IntPtr pDeviceInfo = Marshal.AllocHGlobal(Marshal.SizeOf(d));
Marshal.StructureToPtr(d, pDeviceInfo, false);
IntPtr deviceInfo = GetDeviceInfoKeepConnection(pDeviceInfo);
_DEVICE_INFO result = (_DEVICE_INFO)Marshal.PtrToStructure(deviceInfo, typeof(_DEVICE_INFO));
Marshal.FreeHGlobal(pDeviceInfo);
}
Note that, to ensure that the memory is cleaned up after use, you should use the Marshal.FreeHGlobal method to free the memory that was allocated by Marshal.AllocHGlobal.

Calling C dll from C#, return types slightly different

I've written a dll in C which has functions I can call when referencing the DLL in C#. If I use a basic type like an int it works fine, but I have structs which are slightly different in C# than they are in C due to language differences. Here is an example. This is the function definition in C#:
[DllImport("hello_world_cuda.dll", CharSet = CharSet.Auto)]
public static extern Batch Cut();
And here is it in C:
extern "C" Batch __declspec(dllexport) __stdcall Cut()
You can see the return type Batch is the same, but here is its definition in C#
class Envelope
{
public byte[] Payload;
public byte[] Signature;
}
class Batch
{
public Envelope[] Messages;
public int MsgCount;
}
And here is the definition in C
struct Envelope
{
public:
char* Payload;
char* Signature;
};
struct Batch
{
public:
Envelope* Messages;
int MsgCount;
};
How do I overcome these language differences in order to successfully make the DLL call in C#?
You should define Envelope and Batch as structs in C# too, and apply the StructLaylout attribute:
e.g.:
[StructLayout(LayoutKind.Sequential, Pack=0)]
struct Envelope
{
...
}
Pointers in an unmanaged language do not map to managed arrays as you have done, this is why it is complaining. char is (almost always, with very limited exceptions) an 8 bit value that maps well to byte in C# as you've noticed, but you need to make them pointers in the managed struct as well:
unsafe struct Envelope
{
public byte* Payload;
public byte* Signature;
}

Marshaling native method that return struct

I'm trying to marshal a struct that is returned by my native code but I get System.Runtime.InteropServices.MarshalDirectiveException
It is not a output argument that already answered in other posts, it is return type.
C++ code:
typedef struct
{
bool success;
ErrorCode error_code;
char error_path[1025];
} Result;
DLLEXPORT Result GetResult();
ErrorCode is an enum,
C# equivalent:
[StructLayout(LayoutKind.Sequential)]
public struct Result
{
public byte success;
public ErrorCode error_code;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.I1, SizeConst = 1025)]
public char[] error_path;
}
[DllImport("shared", EntryPoint = "GetReult", CallingConvention = CallingConvention.Cdecl)]
public extern static Result GetResult();
I know the return stucts in C# p/invoke should be blitable type but I don't know if I can make my struct blittable using the Marshaling directives or not.
Is there any way do do that or is something other is wrong with my code?
If there is no way I need to change my API and make the return type as output argument.
Thanks.
You can make it blittable by using a fixed size buffer:
[StructLayout(LayoutKind.Sequential)]
public unsafe struct Result
{
public byte success;
public ErrorCode error_code;
public fixed sbyte error_path[1025];
}
Note that I have used sbyte for the array element type. That's an 8 bit type that matches the unamanged char type which is also an 8 bit type. You used char in your C# which is a 16 bit type.
You may need to convert the fixed size buffer to a string, but exactly how to do that depends upon the encoding that you used. However, there are plenty of articles on that topic (converting fixed size buffer to string) that you can find by web search.

AccessViolationException when accessing unmanaged C++ DLL with C#

I am trying to access a Double Dummy Solver dll (http://privat.bahnhof.se/wb758135/bridge/dll.html ) of unmanaged C++ code from a C# project, but I get the following error message:
An unhandled exception of type 'System.AccessViolationException'
occurred in Dds.Net.dll
Additional information: Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.
The error seems to be around calling the method
Par which takes the three arguments
struct ddTableResults *tablep, struct parResults *presp, int vulnerable
Specifically, related to passing in the 2nd parameter which is described to be:
struct parResults
char parScore[2][16];
char parContractsString [2][128];
Here is my code:
My c# struct:
using System.Runtime.InteropServices;
namespace Dds.Net.Integration
{
[StructLayout(LayoutKind.Sequential)]
internal struct ParResults
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst =32)]
public char[,] parScore;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public char[,] parContractString;
}
}
dllimport to call the function :
[DllImport("dds.dll")]
public static extern int Par(DdTableResults tablep, int vulnerable, ParResults parResults);
Any idea of what I can do to get this working?
Many thanks!
as far as I understand, you c++ signature is
int Par(struct ddTableResults *tablep, struct parResults *presp, int vulnerable)
the c# one maybe is
[DllImport("dds.dll")]
public static extern int Par(ref DdTableResults tablep, ref ParResults parResults, int vulnerable);
c++ wants a poitner to DdTableResults and ParResults, without ref c# will pass structure by value.

pinvoke get data from struct in c

I am using pinvoke in a project I am building.
I need to get data from a function in C, the function gets pointer to a struct.
In my c# I did a class with the appropriate attribute(layountkind.sequntial).
Before the function I do:
mystruct str=new mystruct();
str.Data=new byte[14];
func(str);
I fill the struct in the function but when it exit the function the instance of the class doesn't have the values i filled in c,i check the content of the pointer before i exit the c function and it has the right values.
Below is the prototype of the function:
[DllImport("mydll.dll", CallingConvention=CallingConvention.Cdecl)]
void func([MarshalAs(UnmanagedType.LPStruct)] mystruct str);
My struct in C#:
[StructLayout(LayoutKind.Sequential)]
public class mystruct
{
public ushort familiy;
[MatshalAs(UnmanagedType.ByValArray,SizeConst=14)]
public byte [] data;
}
function and struct in C:
struct sockaddr{
unsigned short familiy;
char data [14];
};
void func(struct sockaddr *info)
{
int i;
char buffer[100]
recvfrom(sockfd,buffer,0,info,&i);//assume i have a global varible sockfd and it is an open socket
}
How can i fix my problem?
The p/invoke declaration is incorrect. The default marshalling is In only. But you need Out marshalling. Otherwise the marshaller won't attempt to marshal the data set by the unmanaged function back to the managed class.
So you can fix the problem by declaring the function like this:
[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void func([Out] mystruct str);
Personally I think that it would be more idiomatic to use a C# struct. I'd declare it like this:
[StructLayout(LayoutKind.Sequential)]
public struct mystruct
{
public ushort family;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=14)]
public byte[] data;
}
And then the function becomes:
[DllImport(dllname, CallingConvention = CallingConvention.Cdecl)]
static extern void func(out mystruct str);
And the call is simply:
mystruct str;
func(out str);

Categories

Resources