我正在使用pinvokes來調用本機代碼。覆蓋C類的數組的默認新運營商#
,如果我要創建我目前做的原生對象的數組以下
public class MyClass() {
// allocate a single myClass;
public MyClass() {
_myClass = myclass_create();
_length = 1;
}
public MyClass(int numArgs) {
//pInvoke call to create an array of myclass;
_myClass = myclass_array_create(UIntPtr);
_length = numArgs;
}
//access the indexed element of myclass
public MyClass this[int index] {
get {
MyClass ret = new MyClass();
ret._myClass = myclass_array_element(this._myClass, (UIntPtr)index);
return ret;
}
}
public int Length {
get {
return _length;
}
}
public void foo(){
//lots of other code
}
[DllImport(DLL_IMPORT_TARGET)]
private static extern IntPtr myclass_create();
[DllImport(DLL_IMPORT_TARGET)]
private static extern IntPtr myclass_array_create(UIntPtr numArgs);
[DllImport(DLL_IMPORT_TARGET)]
private static extern IntPtr myclass_array_element(IntPtr args, UIntPtr index);
// ... more dllimports here ...
//pointer to native object
IntPtr _myClass;
int _length;
}
現在這是使用方法如下:然而
// Create an array of 15 MyClass objects
MyClass myClass = new MyClass(15);
for(int i = 0; i < myClass.Length; ++i) {
//run foo on each object in the array
myClass[i].foo()
}
我有這方面的工作剛剛發現這是有點不同尋常的是,我們需要爲新陣列添加新陣列來調用新陣列。
是否有一種方法可以重寫此類的新運算符,以便可以使用新運算符的典型用法?
我想代碼看起來像這樣
// Create an array of 15 MyClass objects
MyClass[] myClass = new MyClass[15];
for(int i = 0; i < myClass.Length; ++i) {
//run foo on each object in the array
myClass[i].foo()
}
有沒有辦法用我的代碼來做到這一點?
你沒有創建一個數組 - 「MyClass」本身並不是一個數組。你只是簡單地對待它。但是對於每個集合類都是如此。你也不能完成你想要的東西,也不會是一個好主意(它會混淆你的代碼的讀者,它實際上不是一個數組) – 2013-04-25 15:51:47
這段代碼不能編譯。看看你的索引器。 – leppie 2013-04-25 15:52:17
做什麼?你的圖書館,除非你有源無法修改。 myclass_array_create(UIntPtr)只是返回所創建數組的起始地址。你想要做什麼和你在做什麼是完全一樣的。 – 2013-04-25 15:56:19