Showing posts with label Marshall Class. Show all posts
Showing posts with label Marshall Class. Show all posts

2009/07/30

C# - Passing Pointer / Pointer-to-Pointer as Input Parameter to DLL Methods

C Method Declaration

int TestMethod1(Struct1** handle);

int TestMethod2(Struct2* handle);




C# Dll Import

[DllImport("TestMethods.dll")]

private static extern int TestMethod1(ref IntPtr ptrHandle);

[DllImport("TestMethods.dll")]

private static extern int TestMethod2(IntPtr ptrHandle);




C# Calling Dll Methods

IntPtr ptrHandle = IntPtr.Zero;

ptrHandle = Marshal.AllocHGlobal(IntPtr.Size);

TestMethod1(ref ptrHandle);

TestMethod2(ptrHandle);

Marshal.FreeHGlobal(ptrHandle);

2009/07/07

C# - Reading Unmanaged Memory Using Pointer

Marshall Copy Method
Marshal.Copy(IntPtr source, byte[] destination, int startIndex, int endIndex);

C# - Setting & Zeroizing Unmanaged Memory Using Pointer

Unmanaged Memory Setting
Marshal.Copy(byte[] source, int startIndex, IntPtr ptrHandle, int endIndex);



Unmanaged Memory Zeroizing
// IntPtr ptrHandle;
byte[] zeroBytes = new byte[1024];
Marshal.Copy(zeroBytes , 0, ptrHandle, zeroBytes.Length - 1);

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
{
}
}
}
}

Google Analytics

Blog Archive

Followers