水曜日, 7月 14, 2010

Can you call a C# DLL from a C DLL?

Can you call a C# DLL from a C DLL?


C#

//function i want to call 
public static void GuiDelegate(string message)
{
WriteToWPFGui(message);
}

//notice i need to marshall my string from unmanaged <-> managed, my pinvoke sig
public delegate void CppCallback([MarshalAs(UnmanagedType.LPWStr)] string message);

public static void GuiWriter(CppCallback c)
{
GuiWriter(c);
}

//we need to access C++
[DllImport("C:\\projectName.dll", EntryPoint="CSharp_GuiWriter")] via a dll
public static extern void GuiWriter(CppCallback jarg1);

//CppCallback is defined above
public static CppCallback gui_functor;

delegate void StringDelegate(string message);

//delegate assignment
StringDelegate gui_callback = GuiDelegate;
gui_functor
= new CppCallback(gui_callback);

//this points to pinvoke sig -> pinvoke will step into
projName
.GuiWriter(gui_functor);

C++

typedef void (__stdcall *Callback)(PCWSTR);
static Callback gui;

//Assignment of the delegate to the function pointer
__declspec
(dllexport) void __stdcall CSharp_GuiWriter(void * jarg1)
{
Callback arg1 = (Callback) 0 ;
arg1
= (Callback)jarg1;
gui
= arg1;
}

//invocation
(*gui)(_T("make C# print this text"));


Marshaling between Managed and Unmanaged Code

0 件のコメント: