c# - 在 C++ 应用程序中使用 C# dll

标签 c# c++ .net dll

<分区>

我必须替换旧项目中的 DLL。该项目无法更改(向下兼容、其他生产者等)并具有以下方法签名:

typedef UINT(*CALLBACK Initialise)();
Initialise fp_initialise;

typedef UINT(*CALLBACK ReadPosition)(int *ptr_ncolours, float *ptr_pderrs, float *ptr_cderrs);
ReadPosition fp_readposition;

等等... 其中 CALLBACK__stdcall

我的 C# DLL 接口(interface):

[Guid("00005D2D-ABCD-3214-5694-A4EC0005B4D9")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    [ComVisible(true)]
    public interface IMainInterface
    {
        int Initialise();
        unsafe int ReadPosition(ref int ptr_ncolours, float* ptr_pderrs, float* ptr_cderrs);

//...
}

以及我使用接口(interface)的类:

    [ClassInterface(ClassInterfaceType.None)]
    [Guid("04991247-ABCD-ABCD-A4B8-3533D2F264D0")]
    [ComVisible(true)]
    [ProgId("MyDLL.Main")]
    public class Main : IMainInterface
    {
//...
}

在我的新 C# dll 中调用 Initialize(它没有参数)有效,但任何其他方法调用都在没有任何信息的情况下崩溃。

当我从 C++ 应用程序调用它时,当我用新的 C# dll 替换旧的 dll 时,我如何在我的 C# dll 中编写这些方法?

最佳答案

与其通过 COM 公开您的功能,不如使用概述的反向 P/调用技术 here .

这需要对调用代码稍作更改。如果您无法对原始项目二进制文件进行任何更改,您可以创建一个与要替换的 DLL 同名的小型 native DLL,以充当桥梁。

在此桥接 DLL 中公开您的所有 native 函数,并使用反向 P/Invoke 调用您的托管 DLL(其名称当然需要更改为不同的名称。)

关于c# - 在 C++ 应用程序中使用 C# dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25563475/

相关文章:

android - 当我从 native 代码将非 nullptr 传递给 `alBufferData()` 时,OpenAL 应用程序崩溃/挂起

c++ - 没有针对未初始化的 std::atomic<double> 的编译器警告

.net - 为什么 Console.ReadKey() 会阻止在另一个线程中调用的 Console.WriteLine 的输出?

.net - 转换和拆箱有什么区别?

C# unit test akward 运行时

c# - 我如何获得屏幕方向?

c++ - 单向链表 C++ ostream 和 istream -- 输出内存地址

c# - 具有大量参数的 DAL 方法

c# - C# 中的 wtol 等价物

.net - MicrosoftGraph API 无法将消息标记为已读