从C#应用程序调用c ++ DLL

问题描述 投票:0回答:2

我将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代码:

Header: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代码,效果很好。即

Header: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。

c# c++ c++-cli
2个回答
0
投票

您将这个项目托管在某个地方吗?在第一个视图上,我会说您需要先构建c ++项目(仅c ++ !!!),然后再运行C#项目。也许您想在这里看看:Testprojects尤其是“ MessageBox”内容显示了如何在C#中使用C ++。也有一些带有UWP的Testproject。


-1
投票

最简单的方法是创建一个“代理”:一组clear-C函数,这些将调用您的c ++函数。我认为调用c ++函数不是一个好主意:名称修饰从版本到编译器版本都已更改。

© www.soinside.com 2019 - 2024. All rights reserved.