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

调用方法:

相关推荐
矶鹬笛手28 分钟前
(2.1) 信息技术及其发展
sql·计算机网络·c#
u***27612 小时前
C#数据库操作系列---SqlSugar完结篇
网络·数据库·c#
p***h6432 小时前
JavaScript在Node.js中的异步编程
开发语言·javascript·node.js
散峰而望2 小时前
C++数组(二)(算法竞赛)
开发语言·c++·算法·github
Porunarufu2 小时前
Java·关于List
java·开发语言
子不语1802 小时前
Python——函数
开发语言·python
ndjnddjxn2 小时前
Rust学习
开发语言·学习·rust
月光技术杂谈2 小时前
实战:C驱动框架嵌入Rust模块的互操作机制与完整流程
c语言·开发语言·rust·ffi·跨语言·bindgen·互操作
t198751283 小时前
基于MATLAB的指纹识别系统完整实现
开发语言·matlab
笑非不退3 小时前
C# c++ 实现程序开机自启动
开发语言·c++·c#