简体   繁体   English

使用C#项目的一种解决方案中的本机C ++ dll

[英]Native C++ dll in one solution with C# project

I have a source file written in C++, performing some simulation. 我有一个用C ++编写的源文件,可以进行一些模拟。 I would like to create a user interface for this in C#. 我想在C#中为此创建一个用户界面。 How can I have both C++ and C# in a single Visual Studio solution? 如何在单个Visual Studio解决方案中同时拥有C ++和C#?

What I did so far was I created a .NET C# project and solution, and then a native project as a DLL library. 到目前为止,我要做的是创建一个.NET C#项目和解决方案,然后创建一个本机项目作为DLL库。 I have marked the C# project as "Depends on" the C++ dll. 我已将C#项目标记为“取决于” C ++ dll。 I have provided the necessary dllexport directives and imported using DllImport . 我提供了必要的dllexport指令,并使用DllImport导入了。 Everything compiles fine, but when I execute the application, the dll is not found: 一切都可以正常编译,但是当我执行应用程序时,找不到dll:

Unable to load DLL 'xxxx.dll': The specified module could not be found. 无法加载DLL'xxxx.dll':找不到指定的模块。

It is no surprise the DLL is not found, as the application is run from its output directory and the output directories are different for the C# and C++ projects. 找不到DLL也就不足为奇了,因为该应用程序是从其输出目录运行的,并且C#和C ++项目的输出目录是不同的。 I do not want to write an explicit path as my import like `"..\\..\\Debug\\xxxxx.dll". 我不想像““ .. \\ .. \\ Debug \\ xxxxx.dll”一样写一个显式路径作为导入。

Is there some common way how to structure a solution containing native a Dll and C# app so that the C# app can call the native Dll? 有一些常见的方法如何构建包含本机Dll和C#应用程序的解决方案,以便C#应用程序可以调用本机Dll?

If you know that after deployment your C++ DLL will be in the same folder as your C# DLL (or executable), then on simple way to solve the problem is to use the PostBuild event (Project properties, Build events). 如果您知道部署后C ++ DLL与C#DLL(或可执行文件)位于同一文件夹中,那么解决问题的简单方法是使用PostBuild事件(Project属性,Build事件)。

You can add a copy command that will put your C++ DLL into the C# output folder. 您可以添加一个复制命令,该命令会将您的C ++ DLL放入C#输出文件夹中。

I found a very comfortable way, which might have some unexpected drawbacks, but I do not see any so far: I can enable CLR for the C++ DLL project, making it "mixed", even if it in fact does not contain any managed code, and then the project building it can be made a Reference in the C# .NET project. 我找到了一种非常舒适的方法,它可能会有一些意想不到的缺点,但是到目前为止我还没有看到:我可以为C ++ DLL项目启用CLR,使其“混合”,即使它实际上不包含任何托管代码。 ,然后可以在C#.NET项目中将构建它的项目作为参考。

To make the project mixed mode set Configuration Properties / General / Common Language Runtime Support to Common Language Runtime Support (/clr) . 要使项目混合模式,请将Configuration Properties / General / Common Language Runtime SupportCommon Language Runtime Support (/clr)

After this the build system copies the DLL into the application output folder automatically. 此后,生成系统将DLL自动复制到应用程序输出文件夹中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM