Tips for using a C library from C#

前端 未结 6 2208
你的背包
你的背包 2020-12-28 21:57

I\'ve got a library in C which I\'d like to use from C#.

From what I\'ve gleaned off the internet, one idea is to wrap it in a C++ dll, and DllImport that.

6条回答
  •  醉话见心
    2020-12-28 22:36

    Here is a way to send a LOT of numeric data to your C function via a StringBuilder. Just dump your numbers in a StringBuilder, while setting delimiters at appropriate positions et voilá:

    class Program
        {  
            [DllImport("namEm.DLL", CallingConvention = CallingConvention.Cdecl, EntryPoint = "nameEm", 
                CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
            public static extern int nameEm([MarshalAs(UnmanagedType.LPStr)] StringBuilder str);
            static void Main(string[] args)
            {
                int m = 3;
                StringBuilder str = new StringBuilder();
                str.Append(String.Format("{0};", m));
                str.Append(String.Format("{0} {1:E4};", 5, 76.334E-3 ));
                str.Append(String.Format("{0} {1} {2} {3};", 65,45,23,12));
                m = nameEm(str);
            }
        }
    

    And at C-side, pick up the StringBuilder as a char*:

    extern "C"
    {
        __declspec(dllexport) int __cdecl nameEm(char* names)
        {
            int n1, n2, n3[4];
            char *token,
                 *next_token2 = NULL,
                 *next_token = NULL;
            float f;
    
            sscanf_s(strtok_s(names, ";", &next_token), "%d", &n2);
            sscanf_s(strtok_s(NULL, ";", &next_token), "%d %f", &n1, &f);
            // Observe the use of two different strtok-delimiters.
            // the ';' to pick the sequence of 4 integers,
            // and the space to split that same sequence into 4 integers.
            token = strtok_s(strtok_s(NULL, ";", &next_token)," ",&next_token2);
            for (int i=0; i < 4; i++)
            {
                 sscanf_s(token,"%d", &n3[i]);
                 token = strtok_s(NULL, " ",&next_token2);
            }    
            return 0;
        }
    }
    

提交回复
热议问题