kekyo / IL2C

IL2C - A translator for ECMA-335 CIL/MSIL to C language.
Apache License 2.0
401 stars 36 forks source link

How to use array in C#? #90

Closed wch1618 closed 3 years ago

wch1618 commented 3 years ago

I find Array.h in IL2C.Runtime, but using Array.CreateInstance(...) in C# will cause compilation errors

kekyo commented 3 years ago

Is this means how to manipulate array from native (C language) code?

In using C#, IL2C can translate orthodox usage like:

var arr = new int[3];

Example unit test: https://github.com/kekyo/IL2C/blob/master/tests/IL2C.Core.Test.RuntimeSystems/ArrayTypes/ArrayTypes.cs#L72

Your suggested method Array.CreateInstance(...) isn't implemented in IL2C runtime currently. Array manipulation only supported Length, GetUpperBound and GetLowerBound now.

Definition: https://github.com/kekyo/IL2C/blob/master/IL2C.Runtime/include/System/Array.h#L50


In native side, IL2C has il2c_new_array() definition in Array.h . It's bit naive usage but we can use directly. For example:

// var arr = new int[3];
auto arr = il2c_new_array(System_Int32, 3);

// var a1 = arr[1];
auto a1 = il2c_array_item(arr, System_Int32, 1);

// arr[1] = 123;
il2c_array_item(arr, System_Int32, 1) = 123;

// var p = &arr[1];    // Uses only address reference opcodes (ldelema, ...)
auto p = il2c_array_itemptr(arr, System_Int32, 1);
wch1618 commented 3 years ago

Thanks a lot.