You want to use the marshal. GetDelegateForFunctionPointer . You won’t even need to use unsafe code.
delegate void TestCallbackDelegate();
public static void callCallback(int ptr)
{
IntPtr nativePtr = new IntPtr( ptr );
var callback = Marshal.GetDelegateForFunctionPointer<TestCallbackDelegate>( nativePtr );
callback();
}
public static int test(string param)
{
char[] ptrChar = param.ToCharArray();
int ptrInt = 0;
ptrInt = ( ((int)(0xFF00 & (int)ptrChar[1]) | (0x00FF & (int)ptrChar[1])) << 16 ) |
(int)(0xFF00 & (int)ptrChar[0]) | (0x00FF & (int)ptrChar[0]);
callCallback(ptrInt);
}
Although it would be much simpler to just pass the method void*to the C # method, and it will be automatically bound to IntPtr. Here is a minimal example:
C ++
#include <stdio.h>
static void test_callback()
{
printf("test_callback called\n");
}
extern "C" __declspec( dllexport ) void* getPointer()
{
return (void*)&test_callback;
}
WITH#
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport( "invoke.dll" )]
private static extern IntPtr getPointer();
private delegate void TestCallbackDelegate();
static void main()
{
IntPtr ptr = getPointer();
TestCallbackDelegate test_callback = Marshal.GetDelegateForFunctionPointer<TestCallbackDelegate>( ptr );
test_callback();
}
}
DllImport, CLR, , .
. , , OP, . .
#define COBJMACROS
#include <stdio.h>
#include <windows.h>
#include <mscoree.h>
static void test_callback()
{
printf( "test_callback has been called.\n" );
}
int main( void )
{
HRESULT status;
ICLRRuntimeHost *Host;
BOOL Started;
DWORD Result;
Host = NULL;
Started = FALSE;
status = CorBindToRuntimeEx( NULL, NULL, 0, CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (void**)&Host );
if( FAILED( status ) )
goto cleanup;
status = ICLRRuntimeHost_Start( Host );
if( FAILED( status ) )
goto cleanup;
Started = TRUE;
int ptr = (int)&test_callback;
printf( "test_callback is at 0x%X\n", ptr );
char param[5];
param[0] = 0xFF & ( ptr >> 0 );
param[1] = 0xFF & ( ptr >> 8 );
param[2] = 0xFF & ( ptr >> 16 );
param[3] = 0xFF & ( ptr >> 24 );
param[4] = '\0';
status = ICLRRuntimeHost_ExecuteInDefaultAppDomain( Host, L"invoke.dll", L"InteropTesting.Invoker", L"InvokeCallback", (LPCWSTR)param, &Result );
if( FAILED( status ) )
goto cleanup;
cleanup:
if( Started )
ICLRRuntimeHost_Stop( Host );
if( Host != NULL )
ICLRRuntimeHost_Release( Host );
return SUCCEEDED( status ) ? 0 : 1;
}
#
using System;
using System.Runtime.InteropServices;
namespace InteropTesting
{
public static class Invoker
{
private delegate void TestCallbackDelegate();
public static int InvokeCallback( string param )
{
char[] chars = param.ToCharArray();
int ptr = BitConverter.ToInt32( Array.ConvertAll( chars, c => (byte)c ), 0 );
var test_callback = (TestCallbackDelegate)Marshal.GetDelegateForFunctionPointer( new IntPtr( ptr ), typeof( TestCallbackDelegate ) );
test_callback();
return 0;
}
}
}