I have a trouble invoking C function from my C# code. I wanted to add some functionality to VLC player(we use it in our software through vlcdotnet) and cross-compiled it on my ubuntu 12.10 for windows using mingw. I wrote a function, let's call it Foo:
__declspec(dllexport) void Foo(vlc_object_t* bar);
Now I want to call it from C#:
[LibVlcFunction("Foo")]
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void Foo(IntPtr pointer);
........
public LibVlcFunction<Foo> Foo { get; private set; }
......
Foo = new LibVlcFunction<Foo>(myLibVlcCoreDllHandle, VlcVersion);
And it fails. Inside constructor of LibVlcFunction we have combination of GetProcAddress and GetDelegateForFunctionPointer. GetProcAddress fails with "The address of function 'Foo' doesn't exists...." but dumpbin and dep. walker are saying that function exists and her name is not mangled. I tried to write a C++ app that loads a libvlc.dll and gets pointer to my func and it worked. But in C# it fails. What should I do? Any suggestions?
Try not using stdcall and, instead, use cdecl, like this:
extern "C" __declspec(dllexport) void Foo(vlc_object_t* bar);
Your platform invoke call, would like this:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public class libvlc
{
[DllImport("the-vlc.dll", EntryPoint = "Foo")]
extern public static void Foo( IntPtr bar );
}
You will treat vlc_object_t* as opaque handles. You just pass them around. This assumes that vlc_object_t's are allocated and freed in your VLC shared library (i.e. in the DLL).
Related
I was following this example to use a c# delegate as a c++ callback.
My wrapper looks like this:
// GLFWWrapper.h
#pragma once
using namespace System;
namespace GLFWWrapper {
typedef void(__stdcall *KEY_CALLBACK)(int, int, int, int);
public ref class Window {
public:
void setKeyCallback(KEY_CALLBACK fp);
static KEY_CALLBACK csharpKeyCallback;
...
};
}
// GLFWWrapper.cpp
#include "stdafx.h"
#include "GLFWWrapper.h"
namespace GLFWWrapper {
void cppKeyCallback(GLFWwindow * window, int key, int scancode, int action, int mods) {
if (Window::csharpKeyCallback) {
Window::csharpKeyCallback(key, scancode, action, mods);
}
}
void Window::setKeyCallback(KEY_CALLBACK fp) {
csharpKeyCallback = fp;
}
...
}
The cppKeyCallback function is a callback I set in another function (glfwSetKeyCallback(m_ptr, cppKeyCallback);). The csharpKeyCallback is supposed to be the delegate from my C# project. In the example I linked to above it is only explained how I can set a delegate from inside my wrapper. But how can I set the delegate from my C# project? When I try to call setKeyCallback from my C# project I get an error Window.setKeyCallback(?) is not supported by the language.
You seem to be missing the managed part of the instruction:
#pragma managed
public delegate void keyCallback(int, int, int, int);
void Window::setKeyCallback(keyCallback^ fp) {
csharpKeyCallback = fp;
}
In order to pass a reference to a function instance (delegate) from C# to C++\CLI you need to declare it i.e. declare a managed delegate. This can be done either in C# or in C++\CLI.
In your code the KEY_CALLBACK is an unmanaged function declaration. Thus it is "Not supported by the language". C# side cannot use it as a delegate declaration.
In order to avoid such a mess I myself always keep my C++\CLI projects clear of any managed declarations and provide those in an additional C# class library that is referenced from both the C++\CLI wrapper and the C# side.
Edit: Do not forget to put the ^ sign after the managed reference type in the managed method declaration or the compiler is going to bust you with an error 'A delegate type is not allowed here'.
I have a cpp project, a cpp cli project and a c# win forms project. I want to fire a method from my native cpp code and catch it in c# project. How can i do this?
There can be multiple approaches to answer this question, because the dependency requirement between those projects is important. I will try to answer for the most common (i guess) case: in which you already have a native C++ library and you want to use that library in a C# application. In that scenario the C# project depends on the native library project. In such a case you can utilize a gateway cli/c++ library to transform native c++ events to .NET events.
Here is a complete code sample, but before that, please note:
It may not be the shortest solution, but it works fine. Also it can provide more control on transforming native data to .net types.
I used this approach in VS 2005. I dont know if there is a better instrument in newer versions of VS for that specific interoperability purpose.
If your native event is triggered from a thread other than the GUI thread, then beware of that.
The Native Library:
#ifndef _NATIVE_CODE_H_
#define _NATIVE_CODE_H_
//NativeCode.h
//A simple native library which emits only one event.
#include <stdlib.h>
#include <iostream>
using namespace std;
#define NATIVELIBRARY_API __declspec(dllexport)
//An argument class to wrap event parameters
class NativeEventArgs{
public:
//a 32bit integer argument
//any other primitives can be here, just be careful about the byte size
int argInt32;
//null terminated ascii string
const char* argString;
//null terminated wide/unicode string
const wchar_t* argWString;
};
//A simple mechanism to fire an event from native code.
//Your library may have a DIFFERENT triggering mechanism (e.g. function pointers)
class INativeListener
{
public:
virtual void OnEvent(const NativeEventArgs& args)=0;
};
//The actual native library code, source of native events
class NATIVELIBRARY_API NativeCode
{
public:
NativeCode()
:theListener_(NULL)
{}
//Listener registration method
void registerListener(INativeListener* listener) {
theListener_ = listener;
}
//this is the very first source of the event
//native code emits the event via the listener mechanism
void eventSourceMethod() {
//... other stuff
//fire the native event to be catched
if(theListener_){
//prepare event parameters
NativeEventArgs args;
wstring wstr(L"A wide string");
string str("A regular string");
//build-up the argument object
args.argInt32 = 15;
args.argString = str.c_str();
args.argWString = wstr.c_str();
//fire the event using argument
theListener_->OnEvent( args );
}
}
private:
//native code uses a listener object to emit events
INativeListener* theListener_;
};
#endif
Gateway Library Sample:
//GatewayCode.h
//GatewayLibrary is the tricky part,
//Here we listen events from the native library
//and propagate them to .net/clr world
#ifndef _GATEWAY_CODE_H_
#define _GATEWAY_CODE_H_
#include "../NativeLibrary/NativeCode.h" //include native library
#include <vcclr.h> //required for gcroot
using namespace System;
using namespace System::Runtime::InteropServices;
namespace GatewayLibrary{
//.net equvelant of the argument class
public ref class DotNetEventArg{
internal:
//contructor takes native version of argument to transform
DotNetEventArg(const NativeEventArgs& args) {
//assign primitives naturally
argInt32 = args.argInt32;
//convert wide string to CLR string
argWString = Marshal::PtrToStringUni( IntPtr((void*)args.argWString) );
//convert 8-bit native string to CLR string
argString = Marshal::PtrToStringAnsi( IntPtr( (void*)args.argString) );
//see Marshal class for rich set of conversion methods (e.g. buffers)
}
private:
String^ argString;
String^ argWString;
Int32 argInt32;
public:
//define properties
property String^ ArgString {
String^ get() {
return argString;
}
}
property String^ ArgWString {
String^ get() {
return argWString;
}
}
property Int32 ArgInt32 {
Int32 get() {
return argInt32;
}
}
};
//EventGateway fires .net event when a native event happens.
//It is the actual gateway class between Native C++ and .NET world.
//In other words, It RECEIVES NATIVE events, TRANSFORMS/SENDS them into CLR.
public ref class EventGateway {
public:
//ctor, its implementation placed below
EventGateway();
//required to clean native objects
~EventGateway();
!EventGateway();
//the SENDER part
//.net event stuff defined here
delegate void DotNetEventHandler(DotNetEventArg^ arg);
event DotNetEventHandler^ OnEvent;
private:
//our native library code
//notice you can have pointers to native objects in ref classes.
NativeCode* nativeCode_;
//the required device to listen events from the native library
INativeListener* nativeListener_;
internal: //hide from .net assembly
//the RECEIVER part, called when a native event received
void OnNativeEvent(const NativeEventArgs& args){
//you can make necessary transformation between native types and .net types
//create .net argument using native argument
//required conversion is done by DotNetEventArg class
DotNetEventArg^ dotNetArgs = gcnew DotNetEventArg(args);
//fire .net event
OnEvent( dotNetArgs );
}
};
}
//A concrete listener class. we need this class to register native library events.
//Its our second gateway class which connects Native C++ and CLI/C++
//It basically gets events from NativeLibary and sends them to EventGateway
class NativeListenerImp : public INativeListener {
public:
NativeListenerImp(gcroot<GatewayLibrary::EventGateway^> gatewayObj ){
dotNetGateway_ = gatewayObj;
}
//this is the first place we know that a native event has happened
virtual void OnEvent(const NativeEventArgs& args) {
//inform the .net gateway which is responsible of transforming native event to .net event
dotNetGateway_->OnNativeEvent(args);
}
private:
//class member to trigger .net gateway.
//gcroot is required to declare a CLR type as a member of native class.
gcroot<GatewayLibrary::EventGateway^> dotNetGateway_;
};
////ctor and dtors of EventGateway class
GatewayLibrary::EventGateway::EventGateway()
{
nativeCode_ = new NativeCode();
//note; using 'this' in ctor is not a good practice
nativeListener_ = new NativeListenerImp(this);
//register native listener
nativeCode_->registerListener(nativeListener_);
}
GatewayLibrary::EventGateway::~EventGateway()
{
//call the non-deterministic destructor
this->!EventGateway();
}
GatewayLibrary::EventGateway::!EventGateway()
{
//clean up native objects
delete nativeCode_;
delete nativeListener_;
}
#endif
And the final application in C# (or in any other .net language):
//Program.cs
//C# the final evet consumer application
using System;
using System.Collections.Generic;
using System.Text;
using GatewayLibrary;
namespace SharpClient
{
class Program
{
static void Main(string[] args)
{
//create the gateway
EventGateway gateway = new EventGateway();
//listen on .net events using the gateway
gateway.OnEvent += new EventGateway.DotNetEventHandler(gateway_OnEvent);
}
static void gateway_OnEvent( DotNetEventArg args )
{
//use the argument class
Console.WriteLine("On Native Event");
Console.WriteLine(args.ArgInt32);
Console.WriteLine(args.ArgString);
Console.WriteLine(args.ArgWString);
}
}
}
this is my C code
extern "C"
{
__declspec(dllexport) void DisplayHelloFromDLL(string a)
{
printf ("%s\n",a)
}
}
this is my C# code
class HelloWorld
{
[DllImport("TestLib.dll")]
public static extern void DisplayHelloFromDLL(string a);
static void Main ()
{
string a = "Hello";
DisplayHelloFromDLL(a);
}
}
It built successfully but crash like this:
SO,how to use P/invoke to call my own C dll from C#?
Please help,thanx in advance.
First of all your code is C++ rather than C. Your function receives a parameter of type std::string and the use of std::string means that your code is actually C++.
Now this parameter type is the root of your problem. You cannot create a std::string in .net and instead will need to use a char* to pass the string data. The following code is what you need:
C++
__declspec(dllexport) void DisplayHelloFromDLL(char* a)
{
printf("%s\n", a);
}
C#
[DllImport("TestLib.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void DisplayHelloFromDLL(string a);
static void Main ()
{
string a = "Hello";
DisplayHelloFromDLL(a);
}
The default p/invoke marshalling for a .net string is to pass a char* as an [In] parameter. There is no need for the complexity of IntPtr, StringToHGlobalAnsi, FreeHGlobal as suggested by one of the other answers. If you can let the p/invoke marshaller do the work then it is preferable to do so.
Note that you also need to make sure that your calling conventions match. Under the assumption that you have not used any special compiler options when building your C++ code, that code will default to used cdecl calling convention. You can make that match with the CallingConvention parameter to the DllImport attribute.
Please take a look at marshalling string at MSDN
In a nut shell, a C# string doesn't get marshalled as std::string but a char* by default
For one thing the return type is not matching. In C it is void and in C# int.
Change your C++ param type to char* and update your C# code as following
class HelloWorld
{
[DllImport("TestLib.dll")]
public static extern void DisplayHelloFromDLL(IntPtr a);
static void Main ()
{
string a = "Hello";
var ptr = System.Runtime.Marshal.StringToHGlobalAnsi(a);
DisplayHelloFromDLL(ptr);
System.Runtime.Marshal.FreeHGlobal(ptr);
}
}
This one is basic, how do I call the function SubscribeNewsFeed in the following from a C# DllImport?
class LogAppender : public L_Append
{
public:
LogAppender()
: outfile("TestLog.txt", std::ios::trunc | std::ios::out)
, feedSubscribed(false)
{
outfile.setf(0, std::ios::floatfield);
outfile.precision(4);
}
void SubscribeNewsFeed()
{
someOtherCalls();
}
};
I'm unable to figure out how to include the class name when using the DllImport in my C# program here:
class Program
{
[DllImport("LogAppender.dll")]
public static extern void SubscribeNewsFeed();
static void Main(string[] args)
{
SubscribeNewsFeed();
}
}
PInvoke cannot be used to call directly into a C++ function in this way. Instead you need to define an extern "C" function which calls the PInvoke function and PInvoke into that function. Additionally you cannot PInvoke into a class instance method.
C / C++ Code
extern "C" void SubscribeNewsFeedHelper() {
LogAppender appender;
appender.SubscribeNewsFeed();
}
C#
[DllImport("LogAppender.dll")]
public static extern void SubscribeNewsFeedHelper();
P/Invoke doesn't work that way. It only can import C functions. So there are different types of interop between the managed (C#) and native (C++) world. Interop via COM would be a solution - providing a C interface another.
I have an unmanaged dll with a class "MyClass" in it.
Now is there a way to create an instance of this class in C# code? To call its constructor? I tried but the visual studio reports an error with a message that this memory area is corrupted or something.
Thanks in advance
C# cannot create class instance exported from native Dll. You have two options:
Create C++/CLI wrapper. This is .NET Class Library which can be added as Reference to any other .NET project. Internally, C++/CLI class works with unmanaged class, linking to native Dll by standard C++ rules. For .NET client, this C++/CLI class looks like .NET class.
Write C wrapper for C++ class, which can be used by .NET client with PInvoke. For example, over-simplified C++ class:
class MyClass()
{
public:
MyClass(int n){data=n;}
~MyClass(){}
int GetData(){return data;}
private:
int data;
};
C API wrapper for this class:
void* CreateInstance()
{
MyClass* p = new MyClass();
return p;
}
void ReleaseInstance(void* pInstance)
{
MyClass* p = (MyClass*)pInstance;
delete p;
}
int GetData(void* pInstance)
{
MyClass* p = (MyClass*)pInstance;
return p->GetData();
}
// Write wrapper function for every MyClass public method.
// First parameter of every wrapper function should be class instance.
CreateInstance, ReleaseInstance and GetData may be declared in C# client using PInvoke, and called directly. void* parameter should be declared as IntPtr in PInvoke declaration.
The solution is create C++/CLI wrapper like:
#include "DllExportClass.h"
public ref class ManagedOperationHelper
{
public:
double Sum(double add1, double add2)
{
CDllExportClass obj;
double ret=obj.Sum(add1, add2);
return ret;
}
double Mult(double mult1, double mult2)
{
CDllExportClass obj;
double ret=obj.Mult(mult1, mult2);
return ret;
}
};
where CDllExportClass is the class exported from native code. Above is the .h of the C++/CLI. Take care to let find the lib to this dll. Put the dll and the lib in the same directory and compile the C++/CLI code.In the managed code directory put the native dll and the C++/CLI dll. In the managed project put the reference of the C++/CLI project. Instanciate in the maged code the C++/CLI class like:
ManagedOperationHelper obj = new ManagedOperationHelper();
double ret=obj.Sum(10, 20);
It's all.
You can not use unmanged C++ code directly in C#. The interoperability can be done using PInvoke. There are a lot of issues related to this topic, especially when calling functions which have pointers as arguments.
The basic procedure goes like this:
C# part
namespace MyNamespace {
public class Test {
[DllImport("TheNameOfThe.dll")]
public static extern void CreateMyClassInstance();
public void CallIt() {
CreateMyClassInstance(); // calls the unmanged function via PInvoke
}
}
}
C++ part
class MyClass {
public: MyClass() { /** Constructor */ }
};
MyClass* staticObject;
extern "C" void CreateMyObjectInstance() {
staticObject = new MyClass(); // constructor is called
}