Adam,

 

On IRC, you mentioned something about using reflection.  Is IntPtr and DllImport not the best way to go?

 

Here is what I am interested in doing.  I would like to create a class that will hold nothing but pinvoke functions to a native C library named MyLibrary.  I want the class MyLibrary private to the assembly.  I think this is done using the “internal” access modifier on the class.  I am using IntPtr for various structure pointers because the structures are private to the native library.  The only way to know what these structures contain is to look at the source code to the library which we may or may not have.

 

What is the best way to encapsulate the pinvoke calls to a native c library in a class private to an assembly?

 

I will be using this for the native c library libpq.so/pq.dll (PostgreSQL client library) in a class called PostgresLibrary in assembly System.Data.dll

 

My example C# source code follows below:

 

// UseMe.cs – class that makes calls to the C library

using System;

 

namespace MyNamespace

{

public class UseMe

{

                        private callPinvokeMethod

                        {

                                    IntPtr ptrToPrivateStructToTheLibrary;

                                    IntPtr ptrToAnotherPrivateStruct;

           

                                    ptrToPrivateStructToTheLibrary  = MyLibrary.someLibraryFunction (“strvalue”);

                                    ptrToAnotherPrivateStruct = MyLibrary.anotherLibraryFunction (ptrToPrivateStructToTheLibrary);

                        }

}

}

 

// MyLibrary.cs – class to contain pinvoke calls to native c library libmy.so on linux/unix and my.dll on windows

using System;

using System.Runtime.InteropServices;

 

namespace MyNamespace

{

            // using internal to make the class MyLibrary private to the MyNamespace.dll assembly

            internal class MyLibrary

            {

                        [DllImport(“my”)]

                        public static extern IntPtr someLibraryFunction (String value);

                        // PrivateLibraryStruct someLibraryFunction (const char *value);

 

                        [DllImport(“my”)]

                        public static extern IntPtr anotherLibraryFunction (IntPtr privateLibraryStructPtr);

                        // AnotherPrivateLibraryStruct *anotherLibraryFunction (PrivateLibraryStruct *privateLibraryStructPtr);

            }

}

 

Thank you,

Daniel

 

Reply via email to