I've a C# DLL below like. I want to use this C# DLL in C++ Builder.
But I don't know C# Struct and C++ Struct marshalling:
using RGiesecke.DllExport;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace TestLibrary
{
[ComVisible(true)]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MyStruct
{
public int X;
public int Y;
}
public class Class1
{
[DllExport("DoSomething", CallingConvention = CallingConvention.StdCall)]
public static int DoSomething(int x, int y, ref MyStruct myStruct)
{
myStruct.X = 50;
myStruct.Y = 75;
return x + y;
}
}
}
I want to pass "myStruct" parameter from C++ Builder below like.
void __fastcall TForm1::FormCreate(TObject *Sender)
{
struct MyStruct
{
int X;
int Y;
};
int (__stdcall *DoSomething)(int,int,MyStruct);
HINSTANCE dllHandle = NULL;
dllHandle = LoadLibrary( edtdllPath->Text.c_str());
if(dllHandle == NULL) return;
int status = -1;
try
{
DoSomething =(int (__stdcall *)(int,int,MyStruct)) GetProcAddress(dllHandle, "DoSomething");
}
catch(Exception &Err)
{
ShowMessage(Err.Message);
}
if(DoSomething != NULL)
{
try
{
MyStruct myStruct;
status = DoSomething(5,5,myStruct);
String strStatus = status;
ShowMessage(strStatus);
ShowMessage(myStruct.X);
ShowMessage(myStruct.Y);
}
catch(EAccessViolation &err)
{
ShowMessage(err.Message);
}
}
}
When I debug code,myStruct.X and myStruct.Y value is wrong.
Where is my wrong ?
You are not passing your struct as pointer to c#, yet in c# you told that it would be a pointer (ref).
The C# project declares the struct parameter like this:
ref MyStruct myStruct
That marshals as a pointer to the struct. In C++ that means
MyStruct*
So change the declaration of the function pointer variable to be like so:
int (__stdcall *DoSomething)(int,int,MyStruct*);
And use the same type when you cast:
DoSomething =(int (__stdcall *)(int,int,MyStruct*)) GetProcAddress(dllHandle, "DoSomething");
Note that a typedef would serve you better here to avoid repeating yourself. And note also that GetProcAddress does not raise exceptions. It signals errors by returning NULL. You don't check for errors properly.
When you call the function pass the address of the struct:
status = DoSomething(5,5,&myStruct);
It's also a little pointless to declare status and initialise it to -1, but then overwrite that value later. It would be more idiomatic to declare and initialise it like this:
int status = DoSomething(5,5,&myStruct);
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 simple C++ win32 DLL developed in visual studio 2017 and compiled in 64 bit environment having the following code:
typedef struct sum {
struct {
int num1;
int num2;
} nums;
} sum1;
extern "C" {
__declspec(dllexport) int initialize(sum1 *summing)
{
int res;
res = summing->nums.num1 + summing->nums.num2;
return res;
}
}
The above code contains a method which returns the sum of two integers by taking a typedef struct as an argument.
I have a C# client application which consumes this Win32 C++ DLL using PInvoke. Following is the code of my C# client application:
[StructLayout(LayoutKind.Sequential)]
public struct nums
{
public int a;
public int b;
}
[StructLayout(LayoutKind.Sequential)]
public struct mydef
{
public IntPtr sum;
}
public class LibWrap
{
[DllImport("C++.dll", EntryPoint = "initialize")]
public static extern int Initialize(ref mydef mydef);
}
class Program
{
static void Main(string[] args)
{
mydef mydef = new mydef();
nums nums;
nums.a = 6;
nums.b = 6;
IntPtr buffer1 = Marshal.AllocCoTaskMem(Marshal.SizeOf(nums));
Marshal.StructureToPtr(nums, buffer1, false);
mydef.sum = buffer1;
int res = LibWrap.Initialize(ref mydef);
Console.WriteLine(res);
}
}
With the above code, I am expecting '12' as output, but instead I am getting '-1504178328' as output.
I am a C# developer with no experience in C++ at all. Please help me to solve this problem.
Use a simpler P/Invoke wrapper:
public static class LibWrap
{
[DllImport("C++.dll", EntryPoint = "initialize")]
public static extern int Initialize(ref Nums nums);
[StructLayout(LayoutKind.Sequential)]
public struct Nums
{
public int a;
public int b;
}
}
and use it like this:
void CSharpExample()
{
LibWrap.Nums nums;
nums.a = 6;
nums.b = 7;
int res = LibWrap.Initialize(ref nums);
Console.WriteLine(res);
}
In your example, you don't need any memory allocation and marshaling, because:
LibWrap.Nums is a struct, thus local variable nums in CSharpExample() is allocated completely on stack.
passing managed struct LibWrap.Nums by ref to LibWrap.Initialize will pass the pointer to local variable nums on stack.
LibWrap.Initialize is called synchronously, so that the pointer you pass to it isn't used anywhere after LibWrap.Initialize function exits. This is important because the pointer becomes invalid as soon as CSharpExample() exits.
On the C# side, you are not handling the nested struct correctly. Try this instead:
[StructLayout(LayoutKind.Sequential)]
public struct mynums {
public int num1;
public int num2;
}
[StructLayout(LayoutKind.Sequential)]
public struct sum1 {
public mynums nums;
}
public class LibWrap {
[DllImport("C++.dll", EntryPoint = "initialize")]
public static extern int Initialize(ref sum1 summing);
}
class Program {
static void Main(string[] args) {
sum1 mysum;
mysum.nums.num1 = 6;
mysum.nums.num2 = 6;
int res = LibWrap.Initialize(ref mysum);
Console.WriteLine(res);
}
}
That being said, having a struct whose sole data member is another struct is redundant and unnecessary. You should remove the outer struct altogether, eg:
struct nums {
int num1;
int num2;
};
extern "C" {
__declspec(dllexport) int initialize(nums *summing) {
return summing->num1 + summing->num2;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct nums {
public int num1;
public int num2;
}
public class LibWrap {
[DllImport("C++.dll", EntryPoint = "initialize")]
public static extern int Initialize(ref nums summing);
}
class Program {
static void Main(string[] args) {
nums mynums;
mynums.num1 = 6;
mynums.num2 = 6;
int res = LibWrap.Initialize(ref mynums);
Console.WriteLine(res);
}
}
Hi i am having the same problem with abstract class.i am trying to wrap my cpp Dll calls to use in the C# module.
Dll is using the Factory pattern.which contain a class Factory,MiddileWare ,And their costrong textrresponding child class.Could any one help me to start the wrapper. i am stuck in between this.Your help will be appreciated. i am giving the flow here:
MiddleWareFactory.h
#pragma once
#include "MiddleWareConnection.h"
#include "std afx.h"
#ifdef MIDDLEWAREFACTORY_EXPORTS
#define MIDDLEWAREFACTORY_API __declspec(dllexport)
#else
#define MIDDLEWAREFACTORY_API __declspec(dllimport)
#endif
MIDDLEWAREFACTORY_API enum eMiddleWareEngine
{
eRabitMQ = 0,
eZeroMQ,
eActiveMQ
};
// This class is exported from the MiddleWareFactory.dll
class MIDDLEWAREFACTORY_API CMiddleWareFactory
{
public:
CMiddleWareFactory(void);
~CMiddleWareFactory();
// TODO: add your methods here.
//Function to Create the object of Broker module:implemnted the Factory concept.
BOOL CreateInstance(CMiddleWareConnection** pMObj);
int m_eMomEngine;//To define which MOM need to enable.
};
extern MIDDLEWAREFACTORY_API int nMiddleWareFactory;
MIDDLEWAREFACTORY_API int fnMiddleWareFactory(void);
MiddleWareConnection.h
#pragma once
class CMiddleWareConnection
{
public:
virtual ~CMiddleWareConnection(void)
{
}
//Pure virtual fuctions for interfacing
virtual BOOL Connect(int nServerType)=0;
virtual BOOL CreateSessionExchange() = 0;
virtual BOOL CreateQueue(LPCTSTR lpszQueueName) = 0;
virtual BOOL Disconnect() = 0;
virtual BOOL Send(void *MomItem,LPCTSTR lpszKey, int &nSendCount)=0;
virtual BOOL Receive() = 0;
virtual void StopReceiver() = 0;
virtual void GetData(void* pMsg, int &nMsgLen,int nMsgType,int &nReceiveCount)=0;
};
RabbitMQ.h
#pragma once
#include "MiddleWareConnection.h"
#include "Amqp.h"
#pragma comment(lib, "rabbitmq.4.lib")
#define GET_DATA(a){memcpy(&a, pDataPtr, sizeof(a));pDataPtr+=sizeof(a);}
#define GET_DATA_EX(s,n){memcpy(s, pDataPtr, n);pDataPtr+=n;}
typedef struct _ROUTINE_KEY
{
CString RoutingKey;
}ROUTEKEY, *LPROUTEKEY;
class CRabbitMQ :
public CMiddleWareConnection
{
public:
CRabbitMQ(CAppConfig &rConfig);
~CRabbitMQ();
void InitializeRBMQ(CAppConfig &rConfig);//Initialize RBMQ Config;
BOOL Connect(int nServerType);
BOOL Disconnect(void);
BOOL Send(void *MomItem, LPCTSTR lpszKey, int &nSendCount);
BOOL Receive(void);
BOOL CreateQueue(LPCTSTR lpszQueueName);
BOOL CreateSessionExchange();
BOOL BindQueue(LPCTSTR lpszQueue, LPCTSTR lpszExchangeName, LPCTSTR lpszKey);
bool IsConnected(){return m_bConnected;}
void SetKeyQueueCombination( TCHAR *pszQueueName, TCHAR *pszRoutingKey);
void StopReceiver();
bool ReEstablishRMQMWConnection();
void GetData(LPBYTE &pMsg, int &nMsgLen,int &nReceiveCount);
void GetData(void* pMsg, int &nMsgLen,int nMsgType,int &nReceiveCount);
BOOL GetNext_JasonListItem(LPJASON_ITEM pItem);
LPRABBIT_MQ_ITEM GetNextItem();
};
Here i want to expose the rabbitMq class functions[Connect,send,Recieve ete from MiddleWareConnection.h to C# module.
Thanks
below I posted a small code example of a wrapping C++/CLI class. You could create a new C++/CLI project which links your native library and create a class following the example below. This will produce a managed assembly that you could reference from C# side. Hope it helps!
#include <Windows.h>
#include <vcclr.h>
using namespace System;
using namespace System::Text;
using namespace System::Collections::Generic;
using namespace System::Runtime::InteropServices;
public ref class CMiddleWareConnection_Net
{
public:
CMiddleWareConnection_Net()
{
pMiddleWareConnection = NULL;
}
~CMiddleWareConnection_Net()
{
//Release pMiddleWareConnection
if (pMiddleWareConnection)
delete pMiddleWareConnection;
}
void InitializeRBMQ(CAppConfig_Net config)
{
// CAppConfig_Net is another ref class
// which provides a toNative method
// returning a plain C++ CAppConfig object
CAppConfig rConfig = config.toNative();
pMiddleWareConnection = CRabbitMQ(rConfig);
}
bool Connect(int nServerType)
{
return (pMiddleWareConnection->Connect(nServerType) == TRUE);
}
bool Disconnect(void)
{
return (pMiddleWareConnection->Disconnect() == TRUE);
}
bool Send(array<Byte>^ MomItem, String^ lpszKey, int% nSendCount)
{
//Assuming MomItem is a byte array...
unsigned char *pData = new unsigned char[MomItem->Length];
Marshal::Copy(MomItem, 0, IntPtr(pData), MomItem->Length);
//Marshal String^ to LPCSTR
IntPtr ip = Marshal::StringToHGlobalAnsi(lpszKey);
LPCSTR str = static_cast<LPCSTR>(ip.ToPointer());
bool bRet = (pMiddleWareConnection->Send(pData, str, nSendCount) == TRUE);
//Freeing memory
delete[] pData;
Marshal::FreeHGlobal(ip);
return bRet;
}
bool Receive(void)
{
return (pMiddleWareConnection->Receive() == TRUE);
}
/* Other methods */
...
private:
CMiddleWareConnection *pMiddleWareConnection;
};
****MiddleWareFactory.h****
BOOL CreateInstance(CMiddleWareConnection** pMObj)
{
//if( some config value)
*pMObj = new RabbitMq();
// esle
/***other MOm like OBCS,OSCS etec...**/
}
****MiddlewareConnection.h****
have the basic abstract functions....
**Rabbitmq.h**
it is one of the child class.
****Wrapper****
CLRWrapper::CppMathWrapper::CppMathWrapper()
{
cppMath = new cCppMath();
oFact->createInstance(&cppMath);'// here i want to pass the reference & wanna get back the child class type:now i am stuck here..how can we pass/marshal the object:im getting the error
}
BOOL CLRWrapper::CppMathWrapper::connect(type)
{
return (cppMath->Connect(nServerType) == TRUE);
}
..........And so On............
CLR Wrapper.cpp(11) : error C2664: 'Factory::createInstance' : cannot convert parameter 1 from 'cli::interior_ptr' to 'Base **'
1> with
1> [
1> Type=cCppMath *
1> ]
1> Cannot convert a managed type to an unmanaged type
}
instead of this we are using createinstance()[InitializeRBMQ() is inside connect(),so it will be handled inside i think]
void InitializeRBMQ(CAppConfig_Net config)
{
// CAppConfig_Net is another ref class
// which provides a toNative method
// returning a plain C++ CAppConfig object
CAppConfig rConfig = config.toNative();
pMiddleWareConnection = CRabbitMQ(rConfig);
}
C# side
i want to expose :
private static void Main(string[] args)
{
CppMathWrapper wrapper = new CppMathWrapper();
wrapper.connect(0);
}
i tried one example with CPPMath class.In real i am attaching the code below:
CLRWrapper::CppMathWrapper::CppMathWrapper()
{
middlewareConnection *oConn;// MiddleConnection.h pointer
middleWareFactory oFact= new middleWareFactory ();// MiddleWareFactory.h object
oFact->createInstance(&oConn);'// here i want to pass the reference & wanna get back the child class type:now i am stuck here..how can we pass/marshal the object:im getting the error.How could i wrap the object....the same like
}
BOOL CLRWrapper::CppMathWrapper::connect(type)
{
return (oConn->Connect(nServerType) == TRUE);
}
..........And so On............
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
I have a common construct in an unmanaged Win32 C++ DLL:
// FirstElemPtrContainer.h
#include "stdafx.h"
typedef unsigned char elem_type; // a byte
typedef struct FirstElemPtrContainer {
unsigned char num_elems;
void *allocd_ary;
} FirstElemPtrContainer;
The void* in the struct is meant to contain a pointer to the first element of an allocated byte array.
The DLL that uses this definition then exports functions to allocate, populate, and deallocate the struct:
// The exported allocator function.
extern "C" _declspec(dllexport)
FirstElemPtrContainer *BuildStruct(int elem_count)
{
FirstElemPtrContainer *fepc_ptr = new FirstElemPtrContainer;
fepc_ptr->num_elems = elem_count;
elem_type *ary = new elem_type[fepc_ptr->num_elems];
for (int i = 0; i < fepc_ptr->num_elems; i++)
{
ary[i] = ((i + 1) * 5); // multiples of 5
}
fepc_ptr->allocd_ary = ary;
return fepc_ptr;
}
// The exported deallocator function.
extern "C" _declspec(dllexport) void
DestroyStruct(FirstElemPtrContainer *fepc_ptr)
{
delete[] fepc_ptr->allocd_ary;
delete fepc_ptr;
}
These work just fine for a native caller.
In C#, I try to describe this same structure via PInvoke:
[StructLayout(LayoutKind.Sequential)]
public struct FirstElemPtrContainer
{
public byte num_elems;
[MarshalAs(UnmanagedType.LPArray,
ArraySubType = UnmanagedType.U1, SizeConst = 4)]
public IntPtr allocd_ary;
}
... and describe the call interface like so:
public static class Imports
{
[DllImport("MyLib", CallingConvention = CallingConvention.Winapi)]
public static extern IntPtr BuildStruct(int elem_count);
[DllImport("MyLib", CallingConvention = CallingConvention.Winapi)]
public static extern void DestroyStruct(IntPtr fepc_ptr);
}
Now I attempt to call my interface:
class Program
{
const int NUM_ELEMS = 4;
static void Main(string[] args)
{
IntPtr fepc_ptr = Imports.BuildStruct(NUM_ELEMS);
if ( fepc_ptr == IntPtr.Zero )
{
Console.WriteLine("Error getting struct from PInvoke.");
return;
}
FirstElemPtrContainer fepc =
(FirstElemPtrContainer)Marshal.PtrToStructure(fepc_ptr,
typeof(FirstElemPtrContainer));
//...
}
}
The PtrToStructure() call gives the error "Cannot marshal field 'allocd_ary' of type 'MyLibInvoke.FirstElemPtrContainer': Invalid managed/unmanaged type combination (Int/UInt must be paired with SysInt or SysUInt)."
You can see that I've hard-coded a particular number of elements, which we'll assume the caller adheres to. I've also added an ArraySubType clause, though it seems not to make a difference. Why the type mismatch complaint?
Your struct should be declared like this:
[StructLayout(LayoutKind.Sequential)]
public struct FirstElemPtrContainer
{
public byte num_elems;
public IntPtr allocd_ary;
}
it has to be done this way because allocd_ary is a pointer to unmanaged memory and cannot be marshalled by the p/invoke marshaller.
In order to read the contents of allocd_ary you can use Marshal.Copy.
FirstElemPtrContainer fepc = (FirstElemPtrContainer)Marshal.
PtrToStructure(fepc_ptr, typeof(FirstElemPtrContainer));
byte[] ary = new byte[fepc.num_elems];
Marshal.Copy(fepc.allocd_ary, ary, 0, ary.Length);
I suspect that CallingConvention.Winapi is wrong and that you should be using CallingConvention.Cdecl.