0

我创建了一个 C# 应用程序。在这个应用程序中,我想使用/运行来自另一个项目的 C++ API(API 是用宏编码编写的)。我尝试导入该 C++ 项目的 dll 并尝试调用属于该 API 的函数。问题是它抛出“无法找到方法”错误。

如何在 C# 项目中运行 C++ 项目?

4

2 回答 2

2

You can't add a native DLL as a reference to a managed project. You have 3 main options:

  1. Make the native functions available with p/invoke.
  2. Expose the native code through COM.
  3. Compile the native code as a managed C++ assembly.

For any serious amount of code, option 3 is the most productive and effective approach.

于 2012-04-17T06:48:06.550 回答
1

如果通过“运行”,您的意思是一个单独的过程:

使用System.Diagnostics.Process .NET 中可用的类:

myProcess.StartInfo.FileName = "notepad.exe";
myProcess.StartInfo.CreateNoWindow = false;
myProcess.Start();

否则,如果您的意思是使用 C++ 开发的 dll,您可以使用Platform Invoke Services

using System;
using System.Runtime.InteropServices;

class PlatformInvokeTest
{
    //First param is of course either in your PATH, or an absolute path:
    [DllImport("msvcrt.dll", EntryPoint="puts", CallingConvention=CallingConvention.Cdecl)]
    public static extern int PutString(string c);
    [DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
    internal static extern int _flushall();

    public static void Main() 
    {
        PutString("Test");
        _flushall();
    }
}
于 2012-04-17T06:31:11.353 回答