第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 charstr_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*

调用方法:

相关推荐
Chen_harmony22 分钟前
一、C++入门基础
开发语言·c++
学逆向的25 分钟前
远程线程注入
开发语言·jvm·网络安全·win32
阡陌数智41 分钟前
RAG 系统的召回退化:向量库、分块、重排全链路问题排查与优化实践
开发语言·人工智能·语言模型·自然语言处理·推荐算法
geovindu1 小时前
rust: Flyweight Pattern
开发语言·后端·设计模式·rust·享元模式·结构型模式
Escalating_xu1 小时前
【C 语言】字符函数和字符串函数:从 ctype 到 strtok、strerror 全面解析
java·c语言·开发语言
郝学胜-神的一滴2 小时前
C++ Templates 07:编译报错和调试手段与实战技巧
开发语言·c++·后端·软件工程·visual studio
害人终害己2 小时前
Redisson 连接 Redis 失败 报错解决方案
java·开发语言
jimy12 小时前
c++的静态类型和动态类型(二)
开发语言·c++
吠品2 小时前
箭头函数为什么不能 new
开发语言·javascript·原型模式
谢亮_vipxieliang2 小时前
PHP 8 新特性:构造器属性提升与实战
开发语言·后端·php