Is it possible to call a method in c# from c++ DLL ?
I have good communication c# -> C++ , but I would like to be able to initiate a call C++ -> c# to poll some data
my code looks something like this...
host.h
/*
define the exporter for the C API
*/
#ifdef DLL_EXPORT
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
class myClass
{
public:
myCLass(){
//do some initialising
}
~myCLass(){
//do some tidying
}
int getInt(int target) {
switch (target)
{
case 0:
return someIntValue;
case 1:
return someOtherIntValue;
default:
return 0;
}
}
std::string getString(int target) {
switch (target)
{
case 0:
return someStringValue;
case 1:
return someOtherStringValue;
default:
return "";
}
}
}
extern "C" {
DLL_EXPORT myClass* myClassConstructor();
DLL_EXPORT void DestroySpatialser(const myClass* _pContext);
DLL_EXPORT int getInt(myClass* _pContext, int target);
DLL_EXPORT void getString(myClass* _pContext, int target, __out BSTR* returnStr);
}
host.cpp
extern "C" {
myClass* myClassConstructor()
{
return new myClass();
}
void myClassDestructor(const myClass* _pContext)
{
if (_pContext != nullptr)
{
_pContext->~myClass();
delete _pContext;
}
}
//example
int getInt(myClass* _pContext, int target)
{
if (_pContext == nullptr)
{
return K_ERR_INT;
}
return _pContext->getInt(target);
}
void getString(myClass* _pContext, int target, __out BSTR* returnStr)
{
std::string str;
if (_pContext == nullptr)
{
str = K_ERR_CHAR;
}
else {
str = _pContext->getString(target);
}
const std::string stdStr = str;
_bstr_t bstrStr = stdStr.c_str();
*returnStr = bstrStr.copy();
}
}
csharp.cs
private const string dllname = "myhost";
[DllImport(dllname)]
private static extern IntPtr myClassConstructor();
[DllImport(dllname)]
private static extern void myClassDestructor(IntPtr _pContext);
[DllImport(dllname)]
private static extern int getInt(IntPtr _pContext, int target);
[DllImport(dllname)]
private static extern float getFloat(IntPtr _pContext, int target);
[DllImport(dllname, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
extern static void getString(IntPtr _pContext, int target, [MarshalAs(UnmanagedType.BStr)] out String str);
private static IntPtr _pContext;
public static IntPtr Create()
{
_pContext = myClassConstructor();
Debug.Log("_pContextcreated");
return _pContext;
}
public static void Destroy()
{
myClassDestructor(_pContext );
}
private static int _getInt(int target)
{
return getInt(_pContext , target);
}
private static string _getString(int target)
{
String str;
getString(_pContext , target, out str);
return str;
}
This all works fine.
I'd like to add the ability to get a value from the .cs app (it will be a struct of 3 floats) which should be called from the instance of myClass.
I don't want to initiate this on c# side (i know how to do that).
Any advice?
EDIT
I implemented the solution found here
https://forum.unity.com/threads/communicating-c-with-c.89930/#post-586885
with two changes (see comments below for why)
public int whatever = 0;
public delegate int myCallbackDelegate( int n, int m );
private myCallbackDelegate myCallback; // <-- add this line
[DllImport ("DLLImport_CProj")]
private static extern int TakesCallback( myCallbackDelegate fp, int n, int m );
void Awake()
{
myCallback = new myCallbackDelegate( this.myCallback ) // <-- add this
int resp = TakesCallback(myCallback, 10, 20 ); // <-- change to this
Debug.Log( resp );
}
Well, One way I can think of is to pass a JSON string as char array from C++ to C# and then parse it on C# and get the data. it's a communication method both languages are familiar with.
Also, you will need to pass a callback from C# to C++ to allow this like explained in this question.
Let me know if this helps :)
Make your C# types COMVisible, which means you will be able to call them from COM aware C++ code, e.g., using ATL.
Related
I have a DLL developed in C++ that performs some computations. I am trying to link this DLL into my C# application.
I have a struct within a struct which contains a char array (C string). I have a pointer to the object created by the C++ DLL within my C# application.
namespace Test
[StructLayout(LayoutKind.Sequential)]
public unsafe struct Child
{
public float number1;
public float number2;
[MarshalAs(UnmanagedType.LPArray)]
public char[] name;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct DataStructure
{
public Child child;
...
}
.
.
.
public unsafe partial class Form1:Form {
[DllImport("Calculation.dll", CallingConvention = CallingConvention.Cdecl)]
unsafe public static extern IntPtr createInstance();
[DllImport("Calculation.dll", CallingConvention = CallingConvention.Cdecl)]
unsafe public static extern DataStructure* processData(IntPtr source); // Setup of data
[DllImport("Calculation.dll", CallingConvention = CallingConvention.Cdecl)]
unsafe public static extern int calculate(IntPtr calc); // Perform calculation
.
.
public Form2()
{
private void button1_Click_1(object sender, EventArgs e)
{
// test functions
unsafe
{
IntPtr ptr1 = createInstance(); // Returns pointer to the instance
DataStructure* data = processData(ptr1); // Returns pointer to DataStructure object created through DllImport
data->child.number1 = 1.234F; // Works
data->child.number1 = 9.876F; // Works
data->child.name = "......" // This doesn't work!!
int result = calculate(ptr1); // Returns value when name commented
}
}
}
}
If I don't comment name, I get the Error - Cannot take the address of managed object.
If I comment name, I am able to run the calculation without issue.
I wish to update the value of the char array name but can't seem to figure out the solution. Below is my usual C solution. Thanks!
#include "DataStructure.h"
#define DLLNAME "Calculation.dll"
int main(int argc, char** argv) {
HINSTANCE dllHandle = LoadLibraryA(fileNameDll);
const void* ptr1 = 0;
int result = 0;
DataStructure *data;
ptr1 = createInstance();
data = processData(ptr1);
data->child.number1 = 1.234;
data->child.number2 = 9.876;
sprintf(data->child.name, "3104-03");
result = calculate(ptr1);
}
I have a huge C++ structure with a lot of validation code in C++, that I want to import in a C# project. I'm able to transfer all value except the CHAR* and CHAR[].
With a CHAR*, my string is full of chiness caracter BUT, if i go look in memory, my string is there, i can see "This is a test #1".
With a CHAR[x], I can see only the 1rst char, same in memory.
In the following test, i can extract the integer : value1 = data.Value1;
and value 1 is 123, but the the CHAR.
Question: What i miss, why i can't get the value with a char array.
Thank you
The C++ DLL
//This is the main DLL file.
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
extern "C"
{
public struct Data
{
int Value1;
char* pValue2;
char Value3[1024];
};
typedef int( *FN_CCP_INVOKE_NEW_BOARD_OPTIMIZER) (struct Data* data);
FN_CCP_INVOKE_NEW_BOARD_OPTIMIZER _pInvokeCallback;
int __declspec(dllexport) DLLTestCPlusPlus_Initialize()
{
return 0;
}
int __declspec(dllexport) DLLTestCPlusPlus_RegisterDllInvokeProcessCallback(void* fnInvokeCaller)
{
_pInvokeCallback = (FN_CCP_INVOKE_NEW_BOARD_OPTIMIZER)fnInvokeCaller;
struct Data data;
// INT
data.Value1 = 123;
// CHAR*
data.pValue2 = new char[1024];
sprintf(data.pValue2, "This is a test #1");
// CHAR [1024]
sprintf(data.Value3, "This is a test #2");
if (_pInvokeCallback)
{
_pInvokeCallback(&data);
}
return 0;
}
}
And here's the C# program that import the DLL.
using System;
using System.Runtime.InteropServices;
public unsafe struct Data
{
public int Value1;
public char* pValue2;
public fixed char Value3[1024];
}
public static class Interop
{
public delegate Int32 Callback([MarshalAs(UnmanagedType.Struct)] Data data);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetDllDirectory(string lpPathName);
[DllImport("C:\\DATA\\CODE\\ApplicationTestCSharp\\x64\\Debug\\DLLTestCPlusPlus.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern Int32 DLLTestCPlusPlus_Initialize();
[DllImport("C:\\DATA\\CODE\\ApplicationTestCSharp\\x64\\Debug\\DLLTestCPlusPlus.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern Int32 DLLTestCPlusPlus_RegisterDllInvokeProcessCallback([MarshalAs(UnmanagedType.FunctionPtr)] Callback handler);
}
public class MyTest
{
private Interop.Callback _callback = null;
public MyTest()
{
int returnCode = 0;
returnCode = Interop.DLLTestCPlusPlus_Initialize();
_callback = new Interop.Callback(CallbackHandler);
returnCode = Interop.DLLTestCPlusPlus_RegisterDllInvokeProcessCallback(_callback);
}
private Int32 CallbackHandler(Data data)
{
int value1 = 0;
string value2 = "";
string value3 = "";
unsafe
{
// INT
value1 = data.Value1;
// CHAR* - MUST BE "This is a test #1"
value2 = new string(data.pValue2);
// CHAR [1024] - "This is a test #2"
value3 = new string(data.Value3);
}
return 1;
}
}
class Program
{
static void Main(string[] args)
{
MyTest myTest = new MyTest();
}
}
Ok i found it, i made that change in the structure declaration
/*
public char* pValue2;
public fixed char Value3[1024];
*/
[MarshalAs(UnmanagedType.LPStr)] public String pValue2;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)] public String pValue3;
And pull the data like that!
// CHAR* - "This is a test #1";
// value2 = new string(data.pValue2);
value2 = data.pValue2
// CHAR [1024] - "This is a test #2"
//value3 = new string(data.Value3);
value3 = data.pValue3;
I am attempting to invoke an unmanaged DLL and use what it returns for authentication. Could someone help me correct my code to return the correct authentication strings?
I am confused about the struct's, any assistance would be appreciated.
this is my C# code invoking the library
class Wrapper
{
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 1)]
public struct ARSSOUserCredentialsStruct
{
/// int
public int m_nARTCPNum;
public int m_nARRPCNum;
/// string*
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)]
public static string m_szARUserName;
public string m_szARPassword;
public string m_szARAuthenticationstring;
public int m_nARNumberOfServers;
//bool
public bool m_bARUsingPreferenceServer;
}
public struct ARSSOServerInformation
{
/// int
public int m_nARTCPNum;
public int m_nARRPCNum;
/// string*
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)]
public string m_szARServerName;
}
[System.Runtime.InteropServices.DllImportAttribute("ARSSOInfo.dll", EntryPoint = "ARGetSSOLoginCrendentials")]
public static extern System.IntPtr ARGetSSOLoginCrendentials(string m_szARUserName);
public static IntPtr getInfo(string m_szARUserName)
{
IntPtr ptr = ARGetSSOLoginCrendentials(m_szARUserName); // should this be IntPtr?
//return (ARSSOUserCredentialsStruct)(Marshal.PtrToStructure(ptr, typeof(ARSSOUserCredentialsStruct))); // what should type >
// var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(m_szARUserName));
if(ptr != null)
{
Marshal.StructureToPtr(m_szARUserName, ptr, false);
Console.WriteLine("Not null");
Console.WriteLine();
}
else
{
Console.WriteLine("null");
Console.ReadLine();
}
return ptr;
}
class Program
{
static void Main(string[] args)
{
getInfo("jp");
}
}
}
unmanaged dll code which is being called by C# app:
#include <string.h>
#include <stdafx.h>
struct ARSSOServerInformation
{
char * m_szARServerName;
int m_nARTCPNum;
int m_nARRPCNum;
};
struct ARSSOUserCredentialsStruct
{
char* m_szARUserName;
char* m_szARPassword;
char* m_szARAuthenticationString;
bool m_bARUsingPreferenceServer;
int m_nARNumberOfServers;
};
extern "C"
{
__declspec(dllexport) void
ARGetSSOLoginCrendentials(ARSSOUserCredentialsStruct
*pUserCredentialStruct)
{
// The required memory for struct ARSSOUserCredentialsStruct is allocated by user tool,
// This dll just needs to assign values.
// eg:
strcpy(pUserCredentialStruct->m_szARUserName, "Demo");
pUserCredentialStruct->m_nARNumberOfServers = 2;
}
}//End 'extern "C"
extern "C"
{
__declspec(dllexport) void
ARGetSSOServerInformation(ARSSOServerInformation *pServerInfo)
{
// The required memory for struct ARSSOServerInformation is allocated by user tool,
// This dll just needs to assign values.
// eg:
strcpy(pServerInfo[0].m_szARServerName, "ServerName1");
pServerInfo->m_nARTCPNum = 3040; pServerInfo->m_nARRPCNum
= 390622;
strcpy(pServerInfo[1].m_szARServerName, "ServerName2");
}
}//End 'extern "C"
I'm trying to pass a string from C# to C++, using platform invoke.
C++ code:
#include<string>
using namespace std;
extern "C"
{
double __declspec(dllexport) Add(double a, double b)
{
return a + b;
}
string __declspec(dllexport) ToUpper(string s)
{
string tmp = s;
for(string::iterator it = tmp.begin();it != tmp.end();it++)
(*it)-=32;
return tmp;
}
}
C# code:
[DllImport("TestDll.dll", CharSet = CharSet.Ansi, CallingConvention =CallingConvention.Cdecl)]
public static extern string ToUpper(string s);
static void Main(string[] args)
{
string s = "hello";
Console.WriteLine(Add(a,b));
Console.WriteLine(ToUpper(s));
}
I receive a SEHException. Is it impossible to use std::string like this? Should I use char* instead ?
Сorrect decision
C# side:
[DllImport("CppDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr GetString(string s);
public string GetString_(string s)
{
var ptr = GetString(s);
var answerStr = Marshal.PtrToStringAnsi(ptr);
return answerStr;
}
C++ side:
extern "C" __declspec(dllexport) const char* GetString(char* s)
{
string workStr(s);
int lenStr = workStr.length() + 1;
char* answer = new char[lenStr];
const char * constAnswer = new char[lenStr];
strcpy(answer, workStr.c_str());
constAnswer = answer;
return constAnswer;
}
And disable /sdl- in the settings of the cpp project.
One way of doing it without causing a memory leak is using a callback.
C# side:
private delegate bool DLLCallback(IntPtr message);
[DllImport(#"YourLibrary.dll", SetLastError = true, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
private static extern void Receive(DLLCallback callback);
private static bool callback(IntPtr ptr)
{
string result = Marshal.PtrToStringAnsi(ptr);
Console.WriteLine(result);
// If the Heap is used
// Marshal.FreeHGlobal(ptr);
return true;
}
private static void Main(string[] args) {
Receive(callback);
}
C++ side:
extern "C" {
typedef BOOL(__stdcall* OutputCallback)(const char* str);
__declspec(dllexport) void Receive(OutputCallback callback)
{
char buffer[BUFFER_SIZE];
ZeroMemory(buffer, BUFFER_SIZE);
BOOL callbackResult = callback(buffer);
}
}
There are other options. This is a good article about passing strings between managed and unmanaged code: article
I suggest to use char*. Here a possible solution.
If you create another C# function ToUpper_2 as follows
C# side:
[DllImport("TestDll.dll"), CallingConvention = CallingConvention.Cdecl]
private static extern IntPtr ToUpper(string s);
public static string ToUpper_2(string s)
{
return Marshal.PtrToStringAnsi(ToUpper(string s));
}
C++ side:
#include <algorithm>
#include <string>
extern "C" __declspec(dllexport) const char* ToUpper(char* s)
{
string tmp(s);
// your code for a string applied to tmp
return tmp.c_str();
}
you are done!
I am trying to do 2 things: get a return value from a C dll function, and have that same function modify 1 of the members of a structure that is passed to it. After much experimentation I was able to get the function to return a value, but I am still unable to get it to return a modified value to the C# code; the value remains (unmodified) as 0.
I've tried lots of variations (ref, [In,Out], etc) to no avail
using System;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
namespace Vexing.Problem{
public class myIdx : VexingObject {
public myIdx(object _ctx) : base(_ctx) { }
private IPlotObject plot1;
[StructLayout(LayoutKind.Sequential)]
public class PLEX { public int yowser; }
[DllImport("my.dll", CharSet = CharSet.Unicode)]
public static extern int cFunction(
[MarshalAs(UnmanagedType.LPStruct)] PLEX mPlex);
PLEX a;
protected override void Create() { a = new PLEX(); }
protected override void CalcBar() {
int mf = cFunction(a);
plot1.Set(a.yowser); }
}}
// pertinent c dll code
typedef struct s_plex { int yowser;} cplex;
extern "C" __declspec( dllexport )
int cFunction(cplex *Cplex){ Cplex->yowser = 44; return 1;}
Your import declaration is wrong.
Setting the CharSet in your case doesn't make any sense (there are no string parameters in the native function declaration).
If you want to pass class instance, ref/out also must be thrown away (classes being passed by reference).
And the main point: extern "C" __declspec( dllexport ) means CallingConvention.Cdecl.
UPDATE. Here's complete working code sample:
C++ (header):
struct CStruct
{
int myField;
};
extern "C" __declspec( dllexport ) int MyFunction(CStruct *pStruct);
C++ (code):
int MyFunction(CStruct *pStruct)
{
pStruct->myField = 100;
return 1;
}
C#:
[StructLayout(LayoutKind.Sequential)]
class MyStruct
{
public int myField;
};
class Program
{
MyStruct myStruct = new MyStruct();
[DllImport("MyLib.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int MyFunction(MyStruct pStruct);
static void Main(string[] args)
{
var p = new Program();
var result = MyFunction(p.myStruct);
Console.WriteLine("Result: {0}, MyStruct.myField = {1}", result, p.myStruct.myField);
}
}
Prints:
Result: 1, MyStruct.myField = 100