第9篇c#调用c++动态库报错处理

1.报错System.DllNotFoundException

编译c++库如果是x64,c#项目也选x64

c++

c#项目

2.报错System.BadImageFormatException

c#项目属性设置:目标平台x64

编译后,bin目录生成x64文件夹

拷贝c++库到此目录,c++如果依赖其它库也一并拷贝

3.System.AccessViolationException

c#传参数:string给c++函数,或接收返回字符串时,字符串需转换

c++的函数

std::string转char*

td::string str_data = "abcdefg";

char* charArr = new char[str_data.length() + 1];

strcpy(charArr, str_data.c_str());

char*转std:string

char* aa ="abdefg";

std::string str = aa;

char*可直接接收c# string

复制代码
char* __stdcall ImgRotate(char* charstr, int degree)
    {
        std::string imgPath = charstr;
       //const char* chardata = c_Obj.ImgRotate(imgPath, degree).c_str();
        std::string str_data = c_Obj.ImgRotate(imgPath, degree);
        char* charArr = new char[str_data.length() + 1];
        strcpy(charArr, str_data.c_str());
      //  strcpy_s(charArr, sizeof(charArr), str_data.c_str());

        return charArr;
        
    }

c#调用

复制代码
[DllImport("CdtxwVisionLibNet.dll")]
        private static extern int Add(int n1, int n2);
        [DllImport("CdtxwVisionLibNet.dll",EntryPoint = "ImgRotate",CharSet=CharSet.Ansi,CallingConvention = CallingConvention.Cdecl)]
        private static extern IntPtr ImgRotate(string path,int degree);

c#IntPtr对应c++的char*

调用方法:

相关推荐
weixin_462446236 分钟前
使用 Go 实现 SSE 流式推送 + 打字机效果(模拟 Coze Chat)
开发语言·后端·golang
JIngJaneIL25 分钟前
基于springboot + vue古城景区管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
敲敲了个代码32 分钟前
隐式类型转换:哈基米 == 猫 ? true :false
开发语言·前端·javascript·学习·面试·web
专注VB编程开发20年1 小时前
C#全面超越JAVA,主要还是跨平台用的人少
java·c#·.net·跨平台
小信啊啊1 小时前
Go语言切片slice
开发语言·后端·golang
阿华hhh1 小时前
Linux系统编程(标准io)
linux·开发语言·c++
南_山无梅落1 小时前
9.Python3集合(set)增删改查和推导式
java·开发语言
sg_knight1 小时前
拥抱未来:ECMAScript Modules (ESM) 深度解析
开发语言·前端·javascript·vue·ecmascript·web·esm
程序喵大人2 小时前
推荐个 C++ 练习平台
开发语言·c++·工具推荐
阿里嘎多学长2 小时前
2025-12-16 GitHub 热点项目精选
开发语言·程序员·github·代码托管