开发者

Using void pointers as template and function parameters in C#

开发者 https://www.devze.com 2023-01-21 04:43 出处:网络
Being a bit of a C++ fanatic, i am in desperate need of using void pointers in C#. The task at hand requires me to not know the type of a certain variable at compile time.

Being a bit of a C++ fanatic, i am in desperate need of using void pointers in C#. The task at hand requires me to not know the type of a certain variable at compile time. So, i thought about preparing a structure with all the info needed to identify the type at runtime. Now, the idea would work in C++, however, C# isn't quite as C++.:wq In particular, i need to define a:

    private List<KeyValuePair<string, KeyValuePair<string, void*>>> mappings;

The first problem starts here. .Net isn't letting me define eh KeyValuePair as <string, void*>. The error i get is: Error 3 The type 'void*' may not be used as a type argument. The error message is quite straightforward, however, having the possibility of doing this will save me a couple of days of work. The second problem is in the same neighborhood. I need to define this function:

 public unsafe void addMapping(string name, string internal_name, void* storage)

again, not allowed, in this case: Error 2 The type 'void*' may not be used as a t开发者_Go百科ype argument Is there some way around these issues?

Thanks for the help!


In C++, void* can point to anything.

In C#, every thing class, structure, enumeration, and delegate derives from System::Object, so object can refer to any instance. Just use KeyValuePair<string, object>.


As Ben notes, you probably do not actually need to do this crazy thing. The C# type system already supports a universal "object" reference type. You can use the "is" and "as" operators and the "GetType()" method to do runtime type analysis of any managed object. I suspect you are building a device that is unnecessary.

If you really truly do need to track stuff via void pointers, and you really do need to make a generic map of void pointers, then use System.IntPtr as the type argument. An IntPtr is a pointer-sized integer, and you can convert void* to IntPtr and back again without too much difficulty.

0

精彩评论

暂无评论...
验证码 换一张
取 消