You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#调用C++ DLL多函数时出现异常问题求助

问题分析与解决方案

先直接回答你的两个疑问:

  1. 这绝对不是预期行为——C#完全支持同时声明多个P/Invoke外部函数,所以你的问题肯定是代码细节上的错误导致的。
  2. 你的核心错误是:第二个函数print_DB的声明缺少了[DllImport]特性,同时还有一处函数名拼写错误。

具体错误点拆解

看你的C#代码片段:

[DllImport("mytest.dll", CallingConvention = CallingConvention.Cdecl)]
unsafe public static extern void* add_node(void *head, int data);
// 这里的print_DB没有加[DllImport]!
unsafe public static extern void print_DB(void *head);
  • 带有extern关键字的静态方法,如果是用来调用非托管DLL的函数,必须搭配[DllImport]特性,告诉编译器“这个方法的实现来自外部非托管DLL”。
  • 你只给add_node加了[DllImport],而print_DB没有,所以编译器会把它当成一个需要在C#类内部实现的抽象外部方法,但你没有提供实现,因此编译/运行时就会抛出“方法没有实现(no RVA)”的错误。
  • 另外你在Main方法里调用的是printDB(head),但函数声明是print_DB(存在下划线差异),这会导致运行时找不到函数,也需要修正。

修正后的C#代码

namespace example
{
    class test
    {
        [DllImport("mytest.dll", CallingConvention = CallingConvention.Cdecl)]
        unsafe public static extern void* add_node(void* head, int data);

        // 给print_DB也加上DllImport特性,保持调用约定一致
        [DllImport("mytest.dll", CallingConvention = CallingConvention.Cdecl)]
        unsafe public static extern void print_DB(void* head);

        unsafe static void Main(string[] args)
        {
            void* head = null; // 记得初始化head指针
            int a = 1, b = 2, c = 3; // 示例测试数据
            head = add_node(head, a);
            head = add_node(head, b);
            head = add_node(head, c);
            print_DB(head); // 修正函数名拼写,和声明保持一致
        }
    }
}

额外注意事项

  • 你的C++ DLL代码里的extern "C"是正确的,它会关闭C++的名字修饰机制,确保C#能通过原始函数名正确找到DLL里的函数。
  • 确保mytest.dll的路径正确:要么将DLL文件放在C#程序的输出目录下,要么在DllImport特性里指定DLL的完整路径。

内容的提问来源于stack exchange,提问作者Nithin P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:36:29