C动态数组匹配C#类型? [英] C dynamic array matches to which C# type?

查看:74
本文介绍了C动态数组匹配C#类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些旧的C代码,带有一些基本的数据结构:动态数组。

我想把它转换成C#代码。



我应该将哪种类型的C#映射到?



我尝试了什么:



tuptily C#中的ArrayList就是答案。试着看看是否有更好的答案。

解决方案

肯定不是ArrrayList!

问题是动态大小的数组在C(这是我假设您正在使用,因为C没有特定的动态关键字)不是固定元素大小,而ArrayList是 - 它是一个对象的数组,它们实际上是指针,因此根据系统字宽固定为32位或64位。

C代码可以创建一个数组100个元素,每个字符(100个字节),每个int(200,400或800字节),指针(400或800字节)或甚至结构(100 * sizeof(myStruct)字节),以便将其映射到ArrayList将不工作。

您需要将C代码映射到数组或List< T>如果你想从C#中调用C代码,那么在C#中使用适当的宽度数据类型 - 这对于获得大小匹配至关重要。

如果要将C重写为C#然后匹配元素大小并不重要,但是ArrayList仍然是错误的解决方案:它已经过时并且已经存在了很长时间 - 它被List< T>取代了。在.NET V2.0中!


请参阅开源P / Invoke Interop助手:

Managed,Native和COM Interop团队 - 下载P / Invoke Interop助手



-SA

I have some old C code with some basic data structure: dynamic array.
I want to convert it into C# code.

Which type in C# I should map to?

What I have tried:

tuitively ArrayList in C# is the answer. try to see if there is a better answer.

解决方案

Not an ArrrayList, for sure!
The problem is that a dynamically sized array in C (which is what I assume you are using since C doesn't have a specific dynamic keyword) isn't a "fixed" element size, and ArrayList is - it's an Array of object which are effectively pointers and so fixed at 32 or 64 bits depending on system word width.
The C code could create an array of 100 elements, each char (100 bytes), each int (200, 400, or 800 bytes), pointers (400 or 800 bytes) or even a struct (100 * sizeof(myStruct) bytes) so mapping that to an ArrayList will not work.
You need to map C code to an array or List<T> of the appropriate width datatype in C# for it to work, if you want to call the C code from within the C# - it is critical to get the size matching.
If you are rewriting the C into C#, then it's a lot less important to match the element size, but an ArrayList is still the wrong solution: it is obsolete and has been for a long time - it was superseded by the List<T> in .NET V2.0!


Please see open-source P/Invoke Interop Assistant:
Managed, Native, and COM Interop Team — Download P/Invoke Interop Assistant.

—SA


这篇关于C动态数组匹配C#类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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