我有 C# 作为我的前端应用程序,我想从我的 c# 调用 c++ dll,但我收到错误。我在这里发布我的代码,请帮助我解决这个问题:
程序.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 代码时,它工作正常。IE
头文件: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。
感谢您的回答。我通过创建一个包含托管代码的额外类(Wrapper 类)解决了这个问题。这个包装类由 c# 类以与我在问题中提到的方式相同的方式调用。这个包装类比调用 c++ 类并将结果返回给 UI。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句