1

Here is a sample of my C# code. Is there a way to decrease the amount of DllImport attributes?

namespace CSLib
{
    class Program
    {
        static void Main(string[] args)
        {
            CLib.test();
            CLib.test2(3);
            A a = new A() { a = 9, b = 5 };
            CLib.test3(ref a);
        }
    }
    class CLib
    {
        [DllImport("path/to/CDLL", CallingConvention = CallingConvention.Cdecl)]
        public static extern void test();

        [DllImport("path/to/CDLL", CallingConvention = CallingConvention.Cdecl)]
        public static extern void test2(int a);

        [DllImport("path/to/CDLL", CallingConvention = CallingConvention.Cdecl)]
        public static extern void test3(ref A a);
    }

    [StructLayout(LayoutKind.Sequential)]
    struct A
    {
        [MarshalAs(UnmanagedType.I4)]
        public int a, b;
    }
}
  • You could import `LoadLibrary` and `GetProcAddress` and load your imports dynamically.. – Blorgbeard Mar 10 '13 at 22:54
  • @Blorgbeard: i'm a bit confused. Wouldnt it be the same amount of code? –  Mar 10 '13 at 22:56
  • Yes, with one less `[DllImport]`.. perhaps I'm taking you a bit too literally – Blorgbeard Mar 10 '13 at 23:00
  • @Blorgbeard: I'm hoping I can do something like put the import on the class and it assume the name. But all of this code will be generated so I shouldnt mind. However there will be 500+ functions and 200+ structs so it may get very large –  Mar 10 '13 at 23:03
  • -1: The title seems completely arbitrarily applied (i.e. not a real question) – Sam Harwell Mar 10 '13 at 23:20
  • @280Z28: I would have never guessed that. You're kind of right. Hows this? "Shorten amount of DllImport in C#?" –  Mar 11 '13 at 01:15

1 Answers1

2

Either expose the methods as COM methods, or create a C++/CLI wrapper around them.

user1610015
  • 6,561
  • 2
  • 15
  • 18
  • 1
    This doesn't really reduce the complexity though, it just moves it from the caller into the DLL. – Ben Voigt Mar 10 '13 at 23:04
  • Well if you use ATL to create the COM server, most of the code is generated for you, you would only have to write what would be the equivalent of DLL-exported methods. But there's no need to write marshalling instructions like with DllImport. – user1610015 Mar 10 '13 at 23:11