I want to hook a C# method to a C++ event written in the C++ DLL
C++ side
#include
extern "C"
{
typedef void (__stdcall *PFN_MYCALLBACK)();
int __stdcall MyUnmanagedApi(PFN_MYCALLBACK callback);
}
C# side
public delegate void MyCallback();
[DllImport("data_acquisition_sys.dll")]
public static extern void MyUnmanagedApi(MyCallback callback);
static void Main(string[] args) {
MyUnmanagedApi(
delegate()
{
Console.WriteLine("Called back by unmanaged side");
}
);
}
}
I followed the http://blogs.msdn.com/b/davidnotario/archive/2006/01/13/512436.aspx
Error
Unhandled Exception: System.EntryPointNotFoundException: Unable to find an entry point named 'MyUnmanagedApi' in DLL 'data_acquisition_sys.dll'. at affect_detection_sys.Program.MyUnmanagedApi(MyCallback callback) at affect_detection_sys.Program.Main(String[] args) in C:\Users\Public\Docume
For all interested parties, here is a working solution to the problem.
C++ side
extern "C"
{
typedef void (*callback_function)();
callback_function gCBF;
__declspec(dllexport) void StartAcquisition(callback_function callback) {
gCBF = callback;
cout << "Acquisition started" << endl;
}
void DoWork() {
gCBF()
}
}
C# side
[DllImport("data_acquisition_sys.dll", EntryPoint = "StartAcquisition")]
public static extern void StartAcquisition(MyCallback callback);
StartAcquisition(delegate()
{
Console.WriteLine("Called back by unmanaged side ");
}
);
Note that the callback_function is an empty method (), since returning and accepting back ANY data results in a runtime crash. This has been reported in other threads, but the answer hasn't been given.
MyUnmanagedApi returns int and you have declared void. Try this:
public delegate void MyCallback();
[DllImport("data_acquisition_sys.dll")]
public static extern int MyUnmanagedApi(MyCallback callback);
static void Main(string[] args) {
MyUnmanagedApi(
delegate()
{
Console.WriteLine("Called back by unmanaged side");
}
);
}
}
Related
I'm trying to pass a C# method to Rust to be used as a callback.
I've managed to pass a static function and it works fine (see below).
Now I'd like to call an instance method, which means that the trigger function below should also receive an opaque (libc::c_void) this pointer.
How can I get the IntPtr which Rust should pass as the instance pointer to the callback function?
C#
class Program
{
delegate void PrintFn(int x);
public static void Main(string[] args)
{
PrintFn fn = Print;
var ptr = Marshal.GetFunctionPointerForDelegate(fn);
IntPtr handle = IntPtr.Zero;
create(ptr, out handle);
trigger(handle, 3);
}
public static void Print(int x)
{
Console.WriteLine($"C#: {x}");
}
[DllImport(#"/path/to/rust/dll")]
public static extern int create(IntPtr readFn, out IntPtr callback);
[DllImport(#"/path/to/rust/dll")]
public static extern int trigger(IntPtr handle, int x);
}
Rust:
use std::boxed::Box;
pub struct RustCallback {
callback: extern "stdcall" fn(i32),
}
impl RustCallback {
fn new(callback: extern "stdcall" fn(i32)) -> RustCallback {
RustCallback {
callback: read_fn,
}
}
}
pub fn set_output_arg<T>(out: *mut T, value: T) {
unsafe { *out.as_mut().unwrap() = value };
}
#[no_mangle]
pub extern "C" fn create(callback: extern "stdcall" fn(i32), sc: *mut *mut RustCallback) -> u32 {
set_output_arg(sc, Box::into_raw(Box::new(RustCallback::new(callback))));
0
}
#[no_mangle]
pub extern "C" fn trigger(sc: *mut RustCallback, x: i32) -> u32 {
let sc = unsafe { sc.as_mut().unwrap() };
let f = sc.read_fn;
f(x);
0
}
I was dealing with the same code. I found a simpler way than the one you expose, look:
fn operation(number: i32, f: &dyn Fn(i32) -> i32) {
f(number);
}
#[no_mangle]
fn print(number: i32) {
println!("Rust: {}", number);
}
#[no_mangle]
pub extern "C" fn c_print(number: i32, callback: unsafe extern "C" fn(i32) -> i32) {
operation(number, &|n| unsafe { callback(n) });
}
Then, in C#:
delegate void PrintFn(int number);
public static void Run()
{
int number = 1234;
// passing a C# function as parameter of Rust function
c_print(number, Print);
// passing a Rust function as callback inside the same Rust function
print(number);
}
static void Print(int number)
{
Console.WriteLine($"C#: {number}\n");
}
[DllImport(RLIB)] static extern void c_print(int number, PrintFn fn);
[DllImport(RLIB)] static extern void print(int number);
When I started to deal with this, look for: «How to use from C# a Rust function that has another function as a parameter?»
I have written the following C++ shared library:
#include "iostream"
#if defined(_WIN32) || defined(_WIN64)
#define Q_DECL_EXPORT __declspec(dllexport)
#define Q_DECL_IMPORT __declspec(dllimport)
#else
#define Q_DECL_EXPORT
#define Q_DECL_IMPORT
#endif
#ifdef MATINCHESS_LIBRARY
# define MATINCHESS_API Q_DECL_EXPORT
#else
# define MATINCHESS_API Q_DECL_IMPORT
#endif
using namespace std;
string* memory;
extern "C"
{
MATINCHESS_API void Initialize();
MATINCHESS_API void Uninitialize();
MATINCHESS_API void Put(string text);
MATINCHESS_API string Get();
void Initialize()
{
memory = new string;
}
void Uninitialize()
{
delete memory;
}
void Put(string text)
{
memory->assign(text);
}
string Get()
{
return *memory;
}
}
And here is my C# console application:
using System;
using System.Runtime.InteropServices;
namespace MatinChess
{
class MainClass
{
const string MatinChessDLL = "libMatinChessDLL.so";
[DllImport(MatinChessDLL)]
public static extern void Initialize();
[DllImport(MatinChessDLL)]
public static extern void Uninitialize();
[DllImport(MatinChessDLL)]
public static extern void Put(string text);
[DllImport(MatinChessDLL)]
public static extern string Get();
public static void Main (string[] args)
{
Console.WriteLine ("Initializing...");
Initialize ();
Console.WriteLine ("Initialized");
Console.WriteLine ("Write: ");
Put (Console.ReadLine ());
Console.WriteLine ("Value is put.");
Console.WriteLine ("You wrote \"" + Get () + "\"");
Console.ReadKey ();
Console.WriteLine ("Uninitializing...");
Uninitialize ();
Console.WriteLine ("Uninitialized");
}
}
}
It safely initializes and puts the string from ReadLine, but when it wants to invoke Get method, it crashes with a long stack trace.
Please help me to find the issue.
You cannot marshal std::string from C++ to C#. You have to use a character buffer. See this question: Passing strings from C# to C++ dll and back -- minimal example
I have this code in a c++ file, with compiles to a dll.
#include "stdafx.h"
#include "WHUU.h"
#include "stdafx.h"
typedef int (__stdcall * Callback)(const int text);
static int x , y= 0;
Callback Handler = 0;
int getX()
{
return x;
}
void setX(int i)
{
x = i;
}
void setY(int i)
{
y = i;
}
int getY()
{
return y;
}
extern "C" __declspec(dllexport)
void __stdcall SetCallback(Callback handler) {
Handler = handler;
}
extern "C" __declspec(dllexport)
void __stdcall addX(int x) {
setX(x);
}
extern "C" __declspec(dllexport)
void __stdcall addY(int y) {
setY(y);
}
extern "C" __declspec(dllexport)
void __stdcall TestCallback() {
int z = getX() + getY();
int retval = Handler(z);
}
My c# application now has to load this dll on runtime. Add to the callback and call the functions. I dont want to use a class. I could load the class and with
Type[] types = moduleAssembly.GetTypes();
But this overkill! Also c++ is not managed.
I mean its so tiny! (and yes this is an example , but the "real" is just as big as this example).
How do i do that?
Thanks you for your help!
add:
i dont like frameworks (like pinvoke / assembly)
the function names / types are fixed and will never change (think of a driver.dll read write)
this dll is written by customers so it should be as easy as possible!
You could also do it over p/invoke, as example:
[DllImport("unmanaged.dll", CharSet = CharSet.Ansi)]
private extern static int yourFunction(int var1, int var2);
i dont like frameworks (like pinvoke / assembly)
I'll suggest P/Invoke anyway. I don't think there are any reasonable alternatives. Perhaps writing a managed wrapper in managed C++, but really?
When you use P/Invoke the .NET runtime will dynamically load the DLL's that you have specified (and this is done when you first call the function). There is no reason to use P/Invoke to call LoadLibrary first.
You can either use P/Invoke to call the dll directly, or you can create a C++/CLI wrapper for it.
Here's how you can do it using P/Invoke:
Add the compiled dll to your C# project, set its 'Copy to Output Directory' property to 'Copy Always'. and call it like this:
class Program
{
[DllImport("cppdll.dll")]
private static extern void addX(int x);
[DllImport("cppdll.dll")]
private static extern void addY(int y);
static void Main(string[] args)
{
addX(5);
addY(7);
}
}
One way to do this would be through API. Find below an example for the setX and getX method from your sample above.
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern IntPtr LoadLibraryEx(string libraryPath, IntPtr fileHandle, int actionFlag);
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern bool FreeLibrary(IntPtr libraryHandle);
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern IntPtr GetProcAddress(IntPtr dllPointer, string functionName);
IntPtr ptr = IntPtr.Zero;
private delegate void setX (int i);
private delegate int getX();
private setX setXDel;
private getX getXDel;
public Constructor()
{
loadLib();
}
public void YourMethod()
{
setXDel(100);
int y = getXDel();
Console.WriteLine(y.ToString());
}
private void loadLib()
{
string path = "your dll path";
ptr = LoadLibraryEx(path, IntPtr.Zero, 0);
if (ptr == IntPtr.Zero)
throw new Exception("Cannot load dll.");
IntPtr addressPtr = GetProcAddress(ptr, "setX");
setXDel = (setX)Marshal.GetDelegateForFunctionPointer(addressPtr, typeof(setX));
addressPtr = GetProcAddress(unrarPtr, "getX");
getXDel = (getX)Marshal.GetDelegateForFunctionPointer(addressPtr, typeof(getX));
}
public void Dispose()
{
if (ptr != IntPtr.Zero)
{
FreeLibrary(ptr);
}
}
I used P/Invoke, post my own cause the callback was not included by the others. But they were good answers! The C# Applicationhas use this GUI.
The Code for the Application is this : (mind it is a prototype to answer a technical question)
public partial class Form1 : Form
{
private delegate int Callback(int text);
private Callback mInstance; // Ensure it doesn't get garbage collected
[DllImport(#"C:\Visual Studio 2010\Projects\kalkulatorius\Debug\WHUU1.dll")]
private static extern void SetCallback(Callback fn);
[DllImport(#"C:\Visual Studio 2010\Projects\kalkulatorius\Debug\WHUU1.dll")]
private static extern void addX(int x);
[DllImport(#"C:\Visual Studio 2010\Projects\kalkulatorius\Debug\WHUU1.dll")]
private static extern void addY(int y);
[DllImport(#"C:\\Visual Studio 2010\Projects\kalkulatorius\Debug\WHUU1.dll")]
private static extern void TestCallback();
private int Handler(int text)
{
textBox3.Text = text.ToString();
return 42;
}
private void button1_Click(object sender, System.EventArgs e)
{
mInstance = new Callback(Handler); // to set the callback in lib
SetCallback(mInstance); // could also be withhin constructor!
addX(int.Parse(textBox1.Text)); // other people in this thread posted this correct answer
addY(int.Parse(textBox2.Text));
TestCallback();
}
public Form1()
{
InitializeComponent();
}
So if you want to use a c++ lib with functions and callbacks (like in the question posted) you can use this.
But how to change the lib?
The Path to the lib is hardcoded (see [dllImport ......] ). But you
can swop the lib in filesystem. This can happen AFTER you build this
application.
If the lib is not on the given path an exception is thrown. So if
your program wants to use this lib first check the lib is present on the filesystem.
(not included in this simple prototype)
So to switch functionality (swop a driver lib ect) you copy a different lib with the
same name into the given path. (Copy paste - maybe change name)
This solution has the least overhead and is good if you never change the interface of an dll after the application was build!
developers!
I have very strange problem. My project has DLL writen in C++ and a GUI writen in C#. And I have implemented callback for some interoperability. I planed that C++ dll will call C# code in some circumstances. It works... but not long and I cant understand why. The problem marked in comment in C# part
Here the complete code of simplified sample:
C++ DLL:
#include <SDKDDKVer.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
extern "C"
{
typedef void (*WriteSymbolCallback) (char Symbol);
WriteSymbolCallback Test;
_declspec(dllexport) void InitializeLib()
{
Test = NULL;
}
_declspec(dllexport) void SetDelegate(WriteSymbolCallback Callback)
{
Test = Callback;
}
_declspec(dllexport) void TestCall(const char* Text,int Length)
{
if(Test != NULL)
{
for(int i=0;i<Length;i++)
{
Test(Text[i]);
}
}
}
};
C# part:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace CallBackClient
{
class Program
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void WriteToConsoleCallback(char Symbol);
[DllImport("CallbackSketch.dll",CharSet=CharSet.Ansi,CallingConvention=CallingConvention.Cdecl)]
private static extern void InitializeLib();
[DllImport("CallbackSketch.dll",CharSet=CharSet.Ansi,CallingConvention=CallingConvention.Cdecl)]
private static extern void SetDelegate(WriteToConsoleCallback Callback);
[DllImport("CallbackSketch.dll",CharSet=CharSet.Ansi,CallingConvention=CallingConvention.Cdecl)]
private static extern void TestCall(string Text,int Length);
private static void PrintSymbol(char Symbol)
{
Console.Write(Symbol.ToString());
}
static void Main(string[] args)
{
InitializeLib();
SetDelegate(new WriteToConsoleCallback(PrintSymbol));
string test = "Hello world!";
for (int i = 0; i < 15000; i++)
{
TestCall(test, test.Length);// It crashes when i == 6860!!!! Debugger told me about System.NullReferenceException
}
}
}
}
The problem is that it crashes in 6860th iteration! I believe that the problem is lack of my knowlege in the subject. Could sombody help me?
SetDelegate(new WriteToConsoleCallback(PrintSymbol));
Yes, this cannot work properly. The native code is storing a function pointer for the delegate object but the garbage collector cannot see this reference. As far as it is concerned, there are no references to the object. And the next collection destroys it. Kaboom.
You have to store a reference to the object yourself. Add a field in the class to store it:
private static WriteToConsoleCallback callback;
static void Main(string[] args)
{
InitializeLib();
callback = new WriteToConsoleCallback(PrintSymbol);
SetDelegate(callback);
// etc...
}
The rule is that the class that stores the object must have a lifetime at least as long as native code's opportunity to make the callback. It must be static in this particular case, that's solid.
I have simple C++ dll function:
__declspec(dllexport) int tst1(int a);
int tst1(int a)
{
return a + 1;
}
I have C# application that calls it:
[DllImport("Project1.dll")]
public static extern int tst1(int i);
static void Main(string[] args)
{
Console.WriteLine( tst1(1) );
Console.ReadLine();
}
}
Got EntryPointNotFoundException error:
What I do wrong?
The name is getting mangled by C++ decoration. Add extern "C" to prevent the mangling of the name:
extern "C" __declspec(dllexport) int tst1(int a);