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

调用方法:

相关推荐
阿猿收手吧!33 分钟前
【C++】string_view:高效字符串处理指南
开发语言·c++
玄同7651 小时前
我的 Trae Skill 实践|使用 UV 工具一键搭建 Python 项目开发环境
开发语言·人工智能·python·langchain·uv·trae·vibe coding
Yorlen_Zhang1 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
lxl13071 小时前
C++算法(1)双指针
开发语言·c++
不绝1911 小时前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
无小道2 小时前
Qt-qrc机制简单介绍
开发语言·qt
zhooyu2 小时前
C++和OpenGL手搓3D游戏编程(20160207进展和效果)
开发语言·c++·游戏·3d·opengl
HAPPY酷2 小时前
C++ 和 Python 的“容器”对决:从万金油到核武器
开发语言·c++·python
大鹏说大话2 小时前
告别 MSBuild 脚本混乱:用 C# 和 Nuke 构建清晰、可维护的现代化构建系统
开发语言·c#
Mr_sun.2 小时前
Day09——入退管理-入住-2
android·java·开发语言