CPP和C#交互语法速览

CPP和Net交互语法速览

本文通过一些demo来记录常用的参数交互,请记住

^ 托管给NET处理内存
% 我是引用,比如在传递 byte[] 的时候,
String^ 是C#的  string 是c++的

一份教材

image-20220617094148527

How to: Use Arrays in C++/CLI

ref new, gcnew (C++/CLI and C++/CX)

如何:在 C++/CLI 中使用跟踪引用

一些关键字搜索

CLR pass it by reference

关于转换

vector可以和C#的list相互转换

std::stringString^可以相互转换

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
posted @ 2022-06-17 13:09  zongzi10010  阅读(135)  评论(0编辑  收藏  举报