我将C#作为前端应用程序,我想从我的C#中调用c ++ dll,但出现错误。 我在这里发布我的代码,请帮助我解决该问题:
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\\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);
}
}
}
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);
}
代码正在成功构建,但是当我运行此代码时,我得到无法在DLL中找到名为'DisplayHelloFromDLL'的入口点。
我在不使用名称空间和类的情况下编写相同的CPP代码,效果很好。 即
标题:source.h
extern "C"
{
__declspec(dllexport) void DisplayHelloFromDLL(char * name, int appId);
}
c ++类:source.cpp
#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#应用程序中使用具有名称空间和子句的DLL。
答案 0 :(得分:0)
感谢您的回答。 我通过制作一个包含托管代码的额外类(包装器类)解决了该问题。包装类由c#类以与我在问题中提到的相同的方式调用。该包装器类将调用c ++类,然后将结果返回到UI。
答案 1 :(得分:-1)
最简单的方法是创建一个“代理”:一组clear-C函数,这些将调用您的c ++函数。 我认为调用c ++函数不是一个好主意:名称修饰在版本与编译器之间已更改。
答案 2 :(得分:-1)
您是否在某个地方托管了此项目? 在第一个视图上,我会说您需要先构建c ++项目(仅c ++ !!!),然后再运行C#项目。 也许您想在这里看看:Testprojects 尤其是“ MessageBox”东西展示了如何在C#中使用C ++。也有一些带有UWP的Testproject。