在C#中调用VC ++ DLL函数 [英] calling VC++ DLL functions in C#
问题描述
我有一个VC ++ dll,我想用它从c#调用.
我有一个用C ++定义的类.
Hi,
I have a VC++ dll which I want to use to call from c#.
I have a class defined in C++.
/* -----------------------*/
class PropertyPageDlg : public CPropertyPage
{
public:
__declspec(dllexport) void glen();
};
extern "C"
{
__declspec(dllexport) void CZippyPlus_PropertyPageDlg::glen()
{
printf("\n Hi Hello World ");
getchar();
}
}
我想在c#中调用此OnBtnDisconnect函数.
这是我所做的.
I want to call this OnBtnDisconnect function in c#.
Here is what I have done .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace C_sharp
{
class Program
{
[DllImport("PropertySheetApp.dll")]
public static extern void glen();
static void Main(string[] args)
{
Console.WriteLine("This is C# program");
glen();
}
}
}
运行c#程序时出现以下错误.
C_sharp.exe中发生了类型为"System.EntryPointNotFoundException"的未处理的异常
附加信息:在DLL"PropertySheetApp.dll"中找不到名为"glen"的入口点.
感谢您对此提供的任何帮助.
谢谢
I am getting the following error while running c# program.
An unhandled exception of type ''System.EntryPointNotFoundException'' occurred in C_sharp.exe
Additional information: Unable to find an entry point named ''glen'' in DLL ''PropertySheetApp.dll''.
Any help on this is appreciated.
Thanks
推荐答案
无法在C#代码中直接使用C ++类(非托管代码!).您可以间接使用PInvoke来访问您的类型.
基本模式是为C ++类的每个成员函数创建一个关联的非成员函数,该函数调用该成员函数,然后从C#导入并调用该成员.
通常,下一个示例是一个基本示例:
在VC ++中,您应该具有:
类Foo {
公众:
int Bar();
};
Foo * Foo_Create(){返回新的Foo(); }
int Foo_Bar(Foo * pFoo){return pFoo-> Bar(); }
void Foo_Delete(Foo * pFoo){删除pFoo; }
现在将这些方法用于C#代码:
[DllImport("Foo.dll")]
公共静态外部IntPtr Foo_Create();
[DllImport("Foo.dll")]
公共静态外部int Foo_Bar(IntPtr value);
[DllImport("Foo.dll")]
静电静态外部空隙Foo_Delete(IntPtr value);
Hi,
There is no way to directly use a C++ class (unmanaged code!) in C# code. You can use PInvoke in an indirect fashion to access your type.
The basic pattern is that for every member function of you C++ class, to create an associated non-member function which calls the member function, then from C# to import and invoke that member.
In generally a basic example is the next one:
In VC++ you should have:
class Foo {
public:
int Bar();
};
Foo* Foo_Create() { return new Foo(); }
int Foo_Bar(Foo* pFoo) { return pFoo->Bar(); }
void Foo_Delete(Foo* pFoo) { delete pFoo; }
Now using these methods into C# code:
[DllImport("Foo.dll")]
public static extern IntPtr Foo_Create();
[DllImport("Foo.dll")]
public static extern int Foo_Bar(IntPtr value);
[DllImport("Foo.dll")]
pulbic static extern void Foo_Delete(IntPtr value);
这篇关于在C#中调用VC ++ DLL函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!