My c++ source code:
#pragma once
using namespace System;
namespace Test {
public ref class Class1
{
public: int Add(int i, int j)
{
return(i + j);
}
};
}
My C# windows source code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Test;// my c++ dll refernce
namespace WindowsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("Test.dll")]
public static extern int Add(int a, int b);
private void button1_Click(object sender, EventArgs e)
{
int p = Add(1, 2);
}
}
}
I placed the c++ dll in c# application output path i e debug folder.
Please help to find me the error i made in the c++ or c# code.
VulpesPosted Aug 1, 2012, 4:40 AM
VulpesPosted Aug 2, 2012, 2:28 PM
The main problem is that it's not a 'stand-alone' function but a class member.
You would therefore need to add two 'stand-alone' functions to the dll:
1 .To create an object of that class and return a pointer to where it's stored on the unmanaged heap; and
2. To destroy it when you're finished.
The Add method would then need to be called using the ThisCall convention and passed the object pointer as the first argument.
Unfortunately, as it's a C++ dll, the exported names would be mangled so you'd need to look them up with a tool such as dumpbin or Dependency Walker before you could call them from C#. An alternative would be to use the ordinal numbers of the functions though you'd still need these tools to look them up.
In practice, few developers can be bothered with all this and instead create a managed wrapper for the unmanaged class which can then be used directly from C# without the need for DllImport.
sarin sPosted Aug 2, 2012, 2:15 AM
Thank you very much. Now i am able to get the methods with class instance.
If i remove ref keyword then can i get Add method by DllImport attribute ?
sarin sPosted Aug 1, 2012, 12:50 AM
Thank for helping me. I tried the same procedure what ever you explained.
My C++ code i rewrite it as
#pragma once
using namespace System;
namespace Test
{
public class Class1
{
public:int Add(int i, int j)
{
return(i + j);
}
};
}
In C# application i gave reference to C++ dll and added namespace in the source code.
When i instantiate
Class1 cls = new Class1();
cls. ----> i am not getting Add() method
VulpesPosted Jul 31, 2012, 11:21 AM