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

调用方法:

相关推荐
星恒随风1 小时前
Python 基础语法详解(一):从表达式、变量到数据类型
开发语言·笔记·python·学习
888CC++1 小时前
java 并发编程
java·开发语言·python
罗超驿1 小时前
18.Web API 实战:元素与表单属性的获取和修改
开发语言·前端·javascript
被子你放开我2 小时前
CRMEB PHP多商户升级4.0太麻烦了
开发语言·php
阿里嘎多学长2 小时前
2026-06-01 GitHub 热点项目精选
开发语言·程序员·github·代码托管
醒醒该学习了!2 小时前
Anaconda安装教程+第一个python例子
开发语言·python
在繁华处3 小时前
Java从零到熟练(九):并发编程基础
java·开发语言
木头程序员3 小时前
SSM框架学习笔记
java·开发语言·mysql·spring·maven
一起逃去看海吧3 小时前
dify-03
java·linux·开发语言