1. 程式人生 > >C#呼叫非託管函式引數為Void* 時,方法

C#呼叫非託管函式引數為Void* 時,方法

This sample demonstrates how to pass data to an unmanaged function that expects a void pointer as an argument. The sample provides two solutions.

The Void sample uses the following unmanaged function, shown with its original function declaration:

  • SetData exported from PinvokeLib.dll.

    void SetData(DataType typ, void* object)
    

PinvokeLib.dll is a custom unmanaged library that contains an implementation for the previously listed function.

In this sample, the LibWrap class contains an enumeration of types and two managed prototype methods: SetData and SetData2. These methods represent the following approaches for passing data to an unmanaged function expecting a void*

:

  • SetData declares the DataType enumeration and an object. The attribute sets the enumeration to AsAny, which determines the type of an object at run time and marshals the object as that type.

  • SetData2 overloads the method to declare the DataType enumeration and to identify a double or string type. The ref

    ( ByRef in Visual Basic) keyword passes the double by reference.

The App class calls the methods and initializes the enumeration elements. The first approach specifies each enumeration element; the second approach specifies only the largest value type and the string.