CPP和Net交互语法速览

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

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

一份教材

  • http://www.functionx.com/cppcli/Lesson10.htm 参数传递

CPP和Net交互语法速览_第1张图片

How to: Use Arrays in C++/CLI

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

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

一些关键字搜索

CopyCLR pass it by reference

关于转换

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

std::string和String^可以相互转换

ref byte[] bb

C#传递引用数组到CPP,CPP也可以扩展C#的数组

生成的C#的函数签名如下

Copy public voidtestbyte(ref byte[] b1, ref byte[] b2);

C++的API

Copyvoidtestbyte(array^% b1, array^% b2){
    char s[] = "1234568888888888";
    b1 = gcnew array(sizeof(s));

    Array::Resize(b2, sizeof(s));

    //array^ newArray = gcnew array(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++修改,然后打印出来

CopyConsole.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(",");

}

结果如下

Copytestbyte in C#
testbyte startCPP
testbyte endCPP
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#函数签名

Copypublic voidAssign(List l);

C++设计,他会修改追加C#传递的,这里就不用传递引用直接可以传递修改

CopyvoidAssign(Collections::Generic::List^ l){
    std::vector indVariables;
    foreach(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#调用

CopyList parts = new List();
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(",");
}

结果如下

CopyCPP Assign START123CPP Assign END
after fix By cpp1,2,3,4,5,6,

array^

这个可以直接修改里面的内存

C#函数签名

Copypublicintdd(string[] ss);

C++API

Copystd::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#调用

Copystring[] sarray = { "Hello", "layty", "ni", "hao" };
cli.dd(sarray);
foreach (string aPart in sarray)
{
	Console.Write(aPart);
	Console.Write(",");
}

结果

Copycome in4
Hello
layty
ni
hao
HellofixByCPP,laytyfixByCPP,nifixByCPP,haofixByCPP,CPP Assign START

你可能感兴趣的:(C#,c++,开发语言)