CPP和C#交互语法速览
CPP和Net交互语法速览
本文通过一些demo来记录常用的参数交互,请记住
^ 托管给NET处理内存
% 我是引用,比如在传递 byte[] 的时候,
String^ 是C#的 string 是c++的

ref new, gcnew (C++/CLI and C++/CX)
一些关键字搜索
CLR pass it by reference
关于转换#
vector
可以和C#的list
相互转换
std::string
和String^
可以相互转换
ref byte[] bb#
C#传递引用数组到CPP
,CPP
也可以扩展C#的数组
生成的C#的函数签名如下
public void testbyte(ref byte[] b1, ref byte[] b2);
C++的API
void testbyte(array<System::Byte>^% b1, array<System::Byte>^% b2)
{
char s[] = "1234568888888888";
b1 = gcnew array<System::Byte>(sizeof(s));
Array::Resize(b2, sizeof(s));
//array<System::Byte>^ newArray = gcnew array<System::Byte>(sizeof(s));
//Array::Copy(b3, 0, newArray, 0, Math::Min(bb->Length, newsize));
//bb = newArray;
Marshal::Copy((IntPtr)s, b1, 0, sizeof(s));
Marshal::Copy((IntPtr)s, b2, 0, sizeof(s));
}
C#传递后被C++修改,然后打印出来
Console.WriteLine("testbyte in C# ");
byte[] b1= new byte[4];
b1[0] = 1;
b1[1] = 1;
b1[2] = 1;
b1[3] = 1;
byte[] b2 = b1;
Console.WriteLine("testbyte start CPP ");
cli.testbyte(ref b1,ref b2);
Console.WriteLine("testbyte end CPP ");
Console.WriteLine("testbyte show b1 ");
for (int i = 0; i < b1.Length; i++)
{
Console.Write(b1[i]);
Console.Write(",");
}
Console.WriteLine("\ntestbyte show b2 ");
for (int i = 0; i < b2.Length; i++)
{
Console.Write(b2[i]);
Console.Write(",");
}
结果如下
testbyte in C#
testbyte start CPP
testbyte end CPP
testbyte show b1
49,50,51,52,53,54,56,56,56,56,56,56,56,56,56,56,0,
testbyte show b2
49,50,51,52,53,54,56,56,56,56,56,56,56,56,56,56,0,
List<>#
C#函数签名
public void Assign(List<double> l);
C++设计,他会修改追加C#传递的,这里就不用传递引用直接可以传递修改
void Assign(Collections::Generic::List<double>^ l)
{
std::vector<double> indVariables;
for each (double i in l)
{
indVariables.push_back(i);
}
l->Add(4);
l->Add(5);
l->Add(6);
std::cout << "CPP Assign START" << std::endl;
for (auto i : indVariables)
{
std::cout << i << std::endl;
}
std::cout << "CPP Assign END" << std::endl;
}
C#调用
List<double> parts = new List<double>();
parts.Add(1);
parts.Add(2);
parts.Add(3);
cli.Assign(parts); //我是c++ 函数,会修改这个List
Console.WriteLine("after fix By cpp");
foreach (double aPart in parts)
{
Console.Write(aPart);
Console.Write(",");
}
结果如下
CPP Assign START
1
2
3
CPP Assign END
after fix By cpp
1,2,3,4,5,6,
array<String^>^
#
这个可以直接修改里面的内存
C#函数签名
public int dd(string[] ss);
C++API
std::cout << "come in" << std::endl;
std::cout << ss->Length << std::endl;
for (int i = 0; i < ss->Length; i++)
{
Console::WriteLine(ss[i]);
ss[i] = ss[i] + "fixByCPP";
}
C#调用
string[] sarray = { "Hello", "layty", "ni", "hao" };
cli.dd(sarray);
foreach (string aPart in sarray)
{
Console.Write(aPart);
Console.Write(",");
}
结果
come in
4
Hello
layty
ni
hao
HellofixByCPP,laytyfixByCPP,nifixByCPP,haofixByCPP,CPP Assign START
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?