دالة Dllimport C ++ مع المعلمات الافتراضية
-
26-09-2019 - |
سؤال
أحاول استيراد وظيفة من رمز غير مُدار C ++ DLL في تطبيق C# الخاص بي. النموذج الأولي C ++ هو
int somefunction (int param1, int *param2 = NULL);
كيف أعلن ذلك في C# للاستفادة من الطبيعة الافتراضية لـ Param2؟ الرمز التالي لا يعمل. يتم تهيئة Param2 مع القمامة.
DllImportAttribute("mydll.dll", EntryPoint = "somefunction")]
public static extern int somefunction(int param1);
المحلول
إذا كنت تستخدم C# 4.0 ، فإن إجابة DTB هو النهج الصحيح. تمت إضافة C# 4.0 دعم المعلمة الاختيارية وهي تعمل أيضًا مع وظائف Pinvoke.
قبل C# 4.0 ، لا توجد طريقة للاستفادة من المعلمة الاختيارية. أقرب ما يعادل هو تحديد وظيفة واحدة التي توجه إلى الآخر.
[DllImport("mydll.dll", EntryPoint = "somefunction")]
static extern int somefunction(int param1, IntPtr param2);
static int somefunction(int param1) {
someFunction(param1, IntPtr.Zero);
}
نصائح أخرى
محاولة
[DllImport("mydll.dll", EntryPoint = "somefunction")]
static unsafe extern int somefunction(int param1, int* param2 = null);
أو
[DllImport("mydll.dll", EntryPoint = "somefunction")]
static extern int somefunction(int param1, IntPtr param2 = default(IntPtr));
لا تنتمي إلى StackOverflow