呼叫c++;来自C#应用程序的DLL 我有C作为我的前端应用程序,我想从C++中调用C++ DLL,但是我正在出错。 我在这里发布代码,请帮助我解决此问题:
Program.cs呼叫c++;来自C#应用程序的DLL 我有C作为我的前端应用程序,我想从C++中调用C++ DLL,但是我正在出错。 我在这里发布代码,请帮助我解决此问题:,c#,c++,c++-cli,C#,C++,C++ Cli,Program.cs using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCSharp { class Program { [DllImport("C:\\Users\\xy
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestCSharp
{
class Program
{
[DllImport("C:\\Users\\xyz\\source\\repos\\Project1\\Debug\\TestCpp.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void DisplayHelloFromDLL(StringBuilder name, int appId);
static void Main(string[] args)
{
try
{
StringBuilder str = new StringBuilder("name");
DisplayHelloFromDLL(str, str.Length);
str.Clear();
}
catch(DllNotFoundException exception)
{
Console.WriteLine(exception.Message);
}
catch(Exception exception)
{
Console.WriteLine("General exception " + exception.Message);
}
finally
{
Console.WriteLine("Try again");
}
}
}
}
和cpp代码如下所示:
标题:source.h
#include <string>
using namespace std;
extern "C"
{
namespace Test
{
class test
{
public:
test();
__declspec(dllexport) void DisplayHelloFromDLL(char * name, int appId);
}
}
}
extern "C"
{
__declspec(dllexport) void DisplayHelloFromDLL(char * name, int appId);
}
c++类:source.cpp
#include <stdio.h>
#include "source.h"
Test::test::test()
{
printf("This is default constructor");
}
void Test::test::DisplayHelloFromDLL(char * name, int appId)
{
printf("Hello from DLL !\n");
printf("Name is %s\n", name);
printf("Length is %d \n", appId);
}
#include "source.h"
void DisplayHelloFromDLL(char * name, int appId)
{
printf("Hello from DLL !\n");
printf("Name is %s\n", name);
printf("Length is %d \n", appId);
}
< >我如何在我的C应用程序中使用具有命名空间和代码包的动态链接库。 < P>最简单的方法是创建一个“代理”:一组清晰的C函数,这些函数将调用C++函数。
我认为调用C++函数不是好主意:名称修饰从版本到编译器版本。 这个项目是否托管在某个地方? 在第一个视图中,我会说,你需要先构建C++项目(只不过C++)!然后运行C语言项目。 也许您想看看这里: 特别是“消息框”的内容展示了如何用C++语言来使用C++。还有一些关于UWP的测试项目。谢谢您的回答。
我通过创建一个包含托管代码的额外类(包装类)解决了这个问题。c#类调用这个包装器类的方式与我在问题中提到的相同。这个包装类比调用C++类并返回结果到UI。我不知道关于代理,若你们详细说明,那个么这个小例子会对我很有帮助。