2009/06/22

C# - Call C++ Function in DLL with Struct as Input Parameter

C++ DLL Code
#pragma pack
(push)
#pragma pack(1)
typedef struct EmmStruct {
int len;
} EMMSTRUCT, *LPEMMSTRUCT;

typedef struct MyStruct {
int iParam;
long size;
LPEMMSTRUCT lpEmmStructArr;
} MYSTRUCT, *LPMYSTRUCT;
#pragma pack(pop)

extern "C" void __declspec(dllexport) __stdcall TestFunction(LPMYSTRUCT lpMyStruct)
{
lpMyStruct->iParam = 100;
lpMyStruct->size = 10;
lpMyStruct->lpEmmStructArr = new EMMSTRUCT[lpMyStruct->size];
for(int i=0;isize;i++) {
lpMyStruct->lpEmmStructArr[i].len = i;
}
}


C# Codeusing System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace csharptest
{
[StructLayout(LayoutKind.Explicit)]
public struct EmmStruct
{
[FieldOffset(0)]
public int len;
}

[StructLayout(LayoutKind.Explicit)]
public struct MyStruct
{
[FieldOffset(0)]
public int iParam;
[FieldOffset(4)]
public int size;
[FieldOffset(8)]
public IntPtr ptrEmmStruct;
}

class Program
{

[DllImport("dllforcsharp.dll", CallingConvention=CallingConvention.Winapi)]
public extern static void TestFunction(IntPtr ptr);

static void Main(string[] args)
{
try
{
MyStruct s = new MyStruct();
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(s));
Marshal.StructureToPtr(s, ptr, false);

TestFunction(ptr);

s = (MyStruct)Marshal.PtrToStructure(ptr, typeof(MyStruct));

EmmStruct ret;
for (int i = 0; i < ptr2 =" new IntPtr(s.ptrEmmStruct.ToInt32() + 4 * i);
ret = (EmmStruct)Marshal.PtrToStructure(ptr2, typeof(EmmStruct));
}

Marshal.FreeHGlobal(ptr);
}
catch (Exception e)
{
string str = e.Message;
}
finally
{
}
}
}
}

2009/06/11

cmd - Show Current Directory

Show Current Directory CMD
echo %CD%

Google Analytics

Blog Archive

Followers