首页 > 解决方案 > 如何在 C# 包装器中调用 C++ 非托管代码?

问题描述

我有 C# 包装器项目,它使用 C++ 非托管 dll 代码并借助[DllImport]属性和静态外部方法。这是 MSDN 描述的首选方法。

问题是我们只能有一个 c++ 运行器,这意味着我们不能并行运行任务。

如何在不使用dllimport + staticextern 方法的情况下调用非托管 C++,以便当我们实例化其中一个 c# 对象时,它会实例化一个新的 c++ dll 对象

这就是我们现在调用 C++ 代码的方式。

public class FMU : IDisposable
    {

        [DllImport("FMU.dll", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
        private static extern IntPtr Load(string fmuFileName, bool isCoSimulation, AddMessageDelegate messageDelegate, int arrayLocation);

        [DllImport("FMU.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern IntPtr Instantiate(IntPtr fmu, bool isCoSimulation, bool loggingOn, int nCategories, string[] categories);

        [DllImport("kernel32", SetLastError = true)]
        private static extern bool FreeLibrary(IntPtr hModule);

标签: c#c++

解决方案


推荐阅读