如何将C#中的char传递给C ++ DLL [英] How to pass char in C# to C++ DLL

查看:87
本文介绍了如何将C#中的char传递给C ++ DLL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,早上好

i尝试将c#中的参数传递给cpp代码

但这是我在我的cpp中得到的结果

格式错误

hi hello and morning
i try to pass a parameter in c# to cpp code
but this is the result i get in my cpp
the format is wrong

╕τ≡»qsαΦópdsΓ╞òí4ΘáΦTΦF`fsΦ





有人可以告诉我我的代码有什么问题吗

这就是我的工作



我尝试过:


$ c $ b in c#code





can someone tell me what is wrong with my code
this is what i have done

What I have tried:

in c# code

[DllImport("C:\\Users\\user\\Desktop\\mysqlcppConnector\\Debug\\mysqlcppConnector.dll")]
        public static extern string passingChar(StringBuilder charToPass);







passingChar(new StringBuilder("pass me to cpp right now!"));




$ c $ b cpp代码:



in the cpp code:

// please ignore the return type val..
// cause this should return the data from database
// char to pass is the statement of sqlquerry
// this is just a sample code of it
__declspec(dllexport) string passing char(char* charToPass){
printf(charToPass);
return someVal;
}





除此之外

i也用我的c#代码做了这个



besides this
i also did this in my c# code

[DllImport("C:\\Users\\user\\Desktop\\mysqlcppConnector\\Debug\\mysqlcppConnector.dll")]
        public static extern string passingChar([MarshalAs( UnmanagedType.LPStr )] charToPass);







passingChar("pass me to cpp right now!");





这仍然是相同的,我无法得到我的实际字符串尝试传递给mt cpp代码



this is still same and i can not get the actual string that i try to pass to mt cpp code

推荐答案

首先,正确装饰你的DLLImport:

First, decorate your DLLImport correctly:
[DllImport("C:\\Users\\user\\Desktop\\mysqlcppConnector\\Debug\\mysqlcppConnector.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern string passingChar(StringBuilder charToPass);

然后记住C#字符串不是以null结尾 - 所以除非你将字符串长度传递给C ++,否则你需要在结尾处手动添加一个空值,否则C ++代码将不知道有多少字符。一个简单的 printf 或类似的,期望null终止 char * 数据将在没有它的情况下超出缓冲区。

Then remember that C# strings aren't null terminated - so unless you pass the string length to C++, you need to manually add a null value at the end or the C++ code will have no idea how many characters there are. A simple printf or similar that expects null terminated char* data will overrun the buffer without it.


这篇关于如何将C#中的char传递给C ++ DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆