[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

microsoft.public.dotnet.framework.interop

marshalling struct param problem while calling native function

pkpk

10/26/2007 9:18:00 PM

Hello,

I have C# code that calls a native function that takes a struct as a
parameter. It works fine.
Equivalent VB.NET code passes the structure by pointer (instead of copying
it directly onto the stack) and that causes my native code to behave
incorrectly.

This is the declaration of my native function:
extern "C" int __declspec(dllexport) TestFn( MyClass v1, MyClass * pv2 )

This is the definition of MyClass:
#pragma pack( push )
#pragma pack( 4 )
struct MyClass
{
int a;
char b;
float c;
};
#pragma pack( pop )

This is my C# code:
namespace CSharpApplication
{
[StructLayout(LayoutKind.Explicit, Size = 12)]
public struct MyClass
{
[FieldOffset(0)] public int a;
[FieldOffset(4)] public sbyte b;
[FieldOffset(8)] public float c;
};

public class Libwrap
{
[DllImport("ProblemRepro.dll")]
public static extern int TestFn(
MyClass v1,
ref MyClass v2
);
}

class Program
{
static void Main(string[] args)
{
MyClass v1 = new MyClass();
MyClass v2 = new MyClass();

// initialize v1 and v2 members
// ...

// call the function
int r = Libwrap.TestFn(v1, ref v2);
}
}
}

This is my VB code:
Module Module1

<StructLayout(LayoutKind.Explicit, size:=12)> _
Public Class MyClassT
<FieldOffset(0)> Public a As Integer
<FieldOffset(4)> Public b As SByte
<FieldOffset(8)> Public c As Single
End Class

Public Class Libwrap
' I have tried both ways (below) od declaring the function and both
will
' repro the problem

'Declare Function TestFn Lib "ProblemRepro.dll" ( _
' ByVal v1 As MyClassT, _
' ByRef v2 As MyClassT) As Integer

<DllImport("ProblemRepro.dll")> _
Public Shared Function TestFn( _
ByVal v1 As MyClassT, _
ByRef v2 As MyClassT) As Integer
End Function
End Class

Sub Main()
Dim v1 As New MyClassT
Dim v2 As New MyClassT

' initialize v1 and v2
' ...

' call the function
Dim r As Integer
r = Libwrap.TestFn(v1, v2)
End Sub

End Module

When I step through the VB code, I can clearly see that at least v1 is
passed by pointer on the stack. I am not sure about v2, but it is not where
the native code expects it.

What am I doing wrong?

The native DLL is 32-bit, the managed projects are set to target x86.
I am using Windows Vista Ultimate, 64-bit and Visual Studio 2005, SP1 with
vista SP update installed.

1 Answer

(Mattias Sjögren)

10/26/2007 10:08:00 PM

0

>What am I doing wrong?

You're using a struct in C# but a Class in VB.


Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.n... | http://www.dotneti...
Please reply only to the newsgroup.