通过互操作将int数组从C#传递到本机代码

通过互操作将int数组从C#传递到本机代码,c#,.net,visual-c++,c++-cli,interop,C#,.net,Visual C++,C++ Cli,Interop,我有一个废话 public unsafe static int Main() { int[] ai = {1, 2, 3, 4, 5}; UIntPtr stai = (UIntPtr) ai.Length; CManagedStuff obj = new CManagedStuff(); obj.DoSomething(ai, stai); } 然后是ManagedStuff.cpp: void CManagedStuff::DoSomething(int^ _ai, UIn

我有一个废话

public unsafe static int Main()
{
  int[] ai = {1, 2, 3, 4, 5};
  UIntPtr stai = (UIntPtr) ai.Length;
  CManagedStuff obj = new CManagedStuff();
  obj.DoSomething(ai, stai);
}
然后是ManagedStuff.cpp:

void CManagedStuff::DoSomething(int^ _ai, UIntPtr _stai)
{
  // Here I should do something to marshal the int^ to an int*
  pUnmanagedStuff->DoSomething(_ai, (size_t) _stai);
}
void CUnmanagedStuff::DoSomething(int* _ai, size_t _stai)
{
  // Walk and print the _stai ints in _ai
}
和一个非托管的duff.cpp:

void CManagedStuff::DoSomething(int^ _ai, UIntPtr _stai)
{
  // Here I should do something to marshal the int^ to an int*
  pUnmanagedStuff->DoSomething(_ai, (size_t) _stai);
}
void CUnmanagedStuff::DoSomething(int* _ai, size_t _stai)
{
  // Walk and print the _stai ints in _ai
}
如何将
int[]ai
从Main传递到ManagedStuff::DoSomething?我知道该调用中没有封送,因为所有涉及的代码都是管理的

然后我如何在ManagedStuff::DoSomething中封送
int^\u ai
,以调用非ManagedStuff::DoSomething?如果我有一个
int[]\u ai
这个问题答案中的代码可能会有帮助()


可选的,我如何避免使用C++,C++,微软和Windows,停止世界的痛苦?< /P> < P>你必须管理托管资源(你的数组),这样垃圾回收器在使用指针时不会移动它。 在C#中,可以使用

fixed
语句执行此操作:

C++中的钉住与钉住指针一起工作,在一个被管理对象的范围内对其进行PIN。(指向任何元素的指针将锁定整个数组):

//在CManagedStuff中:
pin_ptr_aipined=\u ai

更多信息:

好的,我让它像这样工作:

void CManagedStuff::DoSomething(array<int>^ _ai, UIntPtr _stai)
{
  // Here I should do something to marshal the int^ to an int*
  pin_ptr<int> _aiPinned = &_ai[0];
  pUnmanagedStuff->DoSomething(_aiPinned, (size_t) _stai);
}
void CManagedStuff::DoSomething(数组^ ai,uintpttr)
{
//在这里,我应该做一些事情来将int^封送到int*
pin_ptr_aipined=&u ai[0];
pUnmanagedStuff->DoSomething(_aipined,(尺寸)_stai);
}
首先,传递一个
数组^


其次,正如Tamschi所建议的,使用一个pin指针指向数组中第一个元素的地址。

我只需要指出最初的想法是多么的失败

在本机代码中,可以通过传递第一个元素的地址来传递数组,因为相邻元素可以通过指针算法找到

在托管代码中,元素也邻接存储,但传递
int^
会将元素装箱,并在数组外创建副本。此副本附近不会存储任何其他数组元素


事实上,这也发生在本机跨进程通信中。使用指针算法查找其他元素的诀窍只在过程中工作,而且不普遍适用。

显然,你使用C++ + CLI,而不是直C++,正确吗?对不起,但是我对这个C世界太陌生了,我仍然不能正确理解许多术语和概念。我认为Blah.cs是用不安全的代码(基本上是指针和地址)编写的,CManagedStuff使用C++(C++)/CLI(指向托管内存的指针、类型^风格和指向非托管内存的指针、类型**样式),CUnmanagedStuff完全是C++编写的。实际上,当您在更大的上下文中使用IDisposable模式时,您可能需要该程序的IDisposable模式。但是,首先,我必须能够将一个整数数组从C#code传递到C++/CLI(从Blah.cs传递到ManagedStuff);只要使用
\u ai->Length
@ildjarn就行了。我以前使用过_stai,因为我收到了一个
int^