如何从c#中调用dll中实现的c ++方法?
问题描述:
我用c ++创建了一个dll,我实现了几个方法。我需要在c#项目中使用这个dll,windows form应用程序,以便创建GUI。
我在尝试调用方法时遇到问题。我正在使用[DllImport]并且错误是ocurs无法找到入口点。我已经为dll中的每个方法使用了externc__declspec(dllexoprt)。任何建议都会很棒。
非常感谢!
I have created a dll using c++ where I implemented several methods. I need to use this dll in a c# project, windows form application, in order to create a GUI.
I have problems trying to call the methods. I am using [DllImport] and the error that ocurs is "unable to find an entry point". I have used extern "c" __declspec(dllexoprt) for each method in the dll. Any advice would be great.
Thank you very much!
答
直接使用Interop不是最好的选择C ++项目是你的你必须用C ++开发一些模块。您可以使用C ++ / CLI,它允许您创建混合模式(托管+非托管)项目,*混合非托管代码与托管(ref)类或struct
类型。构建此类项目的结果将是一个双用途模块:它可以通过DLL导入用作具有导出功能的常规DLL,以及通过常规引用我的其他程序集使用的常规CLI程序集。
请参阅我以前的答案:如何在ASP.NET中调用C ++ DLL? [ ^ ]。
参见:
https://msdn.microsoft.com/en-us/library/ms235282.aspx [ ^ ]
http://en.wikipedia.org/wiki/C%2B%2B/CLI [ ^ ],
http://www.ecma-international.org/publications/standards/Ecma-372.htm [ ^ ],
http://www.gotw.ca/publications/C++CLIRationale.pdf [ ^ ]。-SA
Using Interop directly is not the best option is the C++ project is yours and you have to develop some module in C++. You can use C++/CLI instead, which allows you to create a mixed-mode (managed+unmanaged) project freely mixing unmanaged code with managed ("ref") classes orstruct
types. The result of the build of such project will be a dual-purpose module: it can be used through DLL import as a regular DLL with exported functions, as well as the regular CLI assembly used through usual referencing my other assemblies.
Please see my past answer: How to invoke C++ DLL in ASP.NET?[^].
See also:
https://msdn.microsoft.com/en-us/library/ms235282.aspx[^]
http://en.wikipedia.org/wiki/C%2B%2B/CLI[^],
http://www.ecma-international.org/publications/standards/Ecma-372.htm[^],
http://www.gotw.ca/publications/C++CLIRationale.pdf[^].—SA
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct Point {
public int x;
public int y;
}
[StructLayout(LayoutKind.Explicit)]
public struct Rect {
[FieldOffset(0)] public int left;
[FieldOffset(4)] public int top;
[FieldOffset(8)] public int right;
[FieldOffset(12)] public int bottom;
}
class Win32API {
[DllImport("User32.dll")]
public static extern bool PtInRect(ref Rect r, Point p);
}