static void NewCpp() { Console.WriteLine(" Работа с Native class "); ManagedObjectWrapper sow = new ManagedObjectWrapper(); NativeMethods Wrapper = new NativeMethods(); CompareCallback call = new CompareCallback(func); int a = sow.GetStringLength("Первая строка"); int b = sow.GetStringLength("Вторая длинная строка"); Console.WriteLine(Wrapper.Max(a, b, call)); sow.FloatProperty = 20.568f; float ret = sow.FloatProperty; Console.WriteLine(sow.ToString()); Console.WriteLine(" Managed wrapper for native C DLL "); CompareCallback call2 = new CompareCallback(Wrapper.func); a = Wrapper.GetStringLength1("Первая строка"); b = Wrapper.GetStringLength2("Вторая длинная строка"); Console.WriteLine("Делегат статической функции"); Console.WriteLine(Wrapper.Max(a, b, call)); a = Wrapper.GetStringLength1("Первая строка еще длиннее"); Console.WriteLine("Делегат функции-члена"); Console.WriteLine(Wrapper.Max(a, b, call2)); }
public void OrderByDelegate() { Dictionary<string, object> vars = new Dictionary<string, object>(); vars["compare"] = new CompareCallback(CompareObjects); IExpression exp = Expression.Parse("orderBy(#compare)"); object[] input = new object[] { 'b', 1, 2.0, "a" }; Assert.AreEqual(new object[] { 1, 2.0, "a", 'b' }, exp.GetValue(input, vars)); }
public void OrderByDelegate() { var vars = new Dictionary <string, object>(); vars["compare"] = new CompareCallback(CompareObjects); var exp = Expression.Parse("orderBy(#compare)"); var input = new object[] { 'b', 1, 2.0, "a" }; Assert.AreEqual(new object[] { 1, 2.0, "a", 'b' }, exp.GetValue(input, vars)); }
public void OrderByDelegate() { Hashtable vars = new Hashtable(); vars["compare"] = new CompareCallback(CompareObjects); IExpression exp = Expression.Parse("orderBy(#compare)"); object[] input = new object[] { 'b', 1, 2.0, "a" }; Assert.AreEqual(new object[] { 1, 2.0, "a", 'b' }, exp.GetValue(input, vars)); }
static void Main(string[] args) { bool isLoaded = false; const string moduleName = "CppDynamicLinkLibrary"; // Check whether or not the module is loaded. isLoaded = IsModuleLoaded(moduleName); Console.WriteLine("Module \"{0}\" is {1}loaded", moduleName, isLoaded ? "" : "not "); // Call the functions exported from the module. { string str = "HelloWorld"; int length; length = NativeMethods.GetStringLength1(str); Console.WriteLine("GetStringLength1(\"{0}\") => {1}", str, length); length = NativeMethods.GetStringLength2(str); Console.WriteLine("GetStringLength2(\"{0}\") => {1}", str, length); } // Call the callback functions exported from the module. { CompareCallback cmpFunc = new CompareCallback(CompareInts); int max = NativeMethods.Max(2, 3, cmpFunc); // Make sure the lifetime of the delegate instance covers the // lifetime of the unmanaged code; otherwise, the delegate // will not be available after it is garbage-collected, and // you may get the Access Violation or Illegal Instruction // error. GC.KeepAlive(cmpFunc); Console.WriteLine("Max(2, 3) => {0}", max); } // Use the class exported from the module. { CSimpleObjectWrapper obj = new CSimpleObjectWrapper(); obj.FloatProperty = 1.2F; float fProp = obj.FloatProperty; Console.WriteLine("Class: CSimpleObject::FloatProperty = {0:F2}", fProp); } // You cannot unload the C++ DLL CppDynamicLinkLibrary by calling // GetModuleHandle and FreeLibrary. // Check whether or not the module is loaded. isLoaded = IsModuleLoaded(moduleName); Console.WriteLine("Module \"{0}\" is {1}loaded", moduleName, isLoaded ? "" : "not "); }
static void Main(string[] args) { bool isLoaded = false; const string moduleName = "CppDynamicLinkLibrary"; // 检查模块是否被加载 isLoaded = IsModuleLoaded(moduleName); Console.WriteLine("模块 \"{0}\" {1}被加载", moduleName, isLoaded ? "" : "没有"); // 从模块中调用被导出的函数 { string str = "HelloWorld"; int length; length = NativeMethods.GetStringLength1(str); Console.WriteLine("GetStringLength1(\"{0}\") => {1}", str, length); length = NativeMethods.GetStringLength2(str); Console.WriteLine("GetStringLength2(\"{0}\") => {1}", str, length); } // 从模块中调用被导出的回调函数 { CompareCallback cmpFunc = new CompareCallback(CompareInts); int max = NativeMethods.Max(2, 3, cmpFunc); // 确保该委托的实例的生命周期涵盖整个非托管代码 // 否则,该委托将无法使用,在垃圾回收后。 // 你可能会收到访问冲突或非法指令错误 GC.KeepAlive(cmpFunc); Console.WriteLine("Max(2, 3) => {0}", max); } // 从模块中使用被导出类. { CSimpleObjectWrapper obj = new CSimpleObjectWrapper(); obj.FloatProperty = 1.2F; float fProp = obj.FloatProperty; Console.WriteLine("Class: CSimpleObject::FloatProperty = {0:F2}", fProp); } // 你不通过调用GetModuleHandle 和 FreeLibrary // 能卸载C++ DLL CppDynamicLinkLibrary // 检查模块是否被加载。 isLoaded = IsModuleLoaded(moduleName); Console.WriteLine("模块 \"{0}\" {1}被加载", moduleName, isLoaded ? "" : "没有"); }
/// <summary> /// A simple stable sorting routine - far from being efficient, only for small collections. /// </summary> /// <remarks> /// Sorting is not(!) done in-place. Instead a sorted copy of the original input is returned. /// </remarks> /// <param name="input">input collection of items to sort</param> /// <param name="comparer">the <see cref="CompareCallback"/> for comparing 2 items in <paramref name="input"/>.</param> /// <returns>a new collection of stable sorted items.</returns> public static void StableSortInPlace(IList input, CompareCallback comparer) { ArrayList ehancedInput = new ArrayList(); IEnumerator it = input.GetEnumerator(); int index = 0; while (it.MoveNext()) { ehancedInput.Add(new Entry(index, it.Current)); index++; } ehancedInput.Sort(Entry.GetComparer(comparer)); for (int i = 0; i < ehancedInput.Count; i++) { input[i] = ((Entry)ehancedInput[i]).Value; } }
// The compare callback should be instead -> IComparer<T>? comparer public extern void Sort(CompareCallback <T> compareCallback);
public void Sort(CompareCallback compareCallback) { }
public static IComparer GetComparer(CompareCallback innerComparer) { return(new EntryComparer(innerComparer)); }
public EntryComparer(CompareCallback innerComparer) { this.innerComparer = innerComparer; }
static void Main(string[] args) { bool isLoaded = false; const string moduleName = "CppDynamicLinkLibrary"; // Check whether or not the module is loaded. isLoaded = IsModuleLoaded(moduleName); Console.WriteLine("Module \"{0}\" is {1}loaded", moduleName, isLoaded ? "" : "not "); // // Access the global data exported from the module. // // P/Invoke does not allow you to access the global data exported // from a DLL module. // // Call the functions exported from the module. // string str = "HelloWorld"; int length; length = NativeMethod.GetStringLength1(str); Console.WriteLine("GetStringLength1(\"{0}\") => {1}", str, length); length = NativeMethod.GetStringLength2(str); Console.WriteLine("GetStringLength2(\"{0}\") => {1}", str, length); // P/Invoke the stdcall API, MessageBox, in user32.dll. MessageBoxResult msgResult = NativeMethod.MessageBox( IntPtr.Zero, "Do you want to ...", "CSPInvokeDll", MessageBoxOptions.OkCancel); Console.WriteLine("user32!MessageBox => {0}", msgResult); // P/Invoke the cdecl API, printf, in msvcrt.dll. Console.Write("msvcrt!printf => "); NativeMethod.printf("%s!%s\n", "msvcrt", "printf"); // // Call the callback functions exported from the module. // // P/Invoke a method that requires callback as one of the args. CompareCallback cmpFunc = new CompareCallback(Max); int max = NativeMethod.CompareInts(2, 3, cmpFunc); // Make sure the lifetime of the delegate instance covers the // lifetime of the unmanaged code; otherwise, the delegate // will not be available after it is garbage-collected, and you // may get the Access Violation or Illegal Instruction error. GC.KeepAlive(cmpFunc); Console.WriteLine("Max(2, 3) => {0}", max); // // Use the class exported from the module. // // There is no easy way to call the classes in a native C++ DLL // module through P/Invoke. Visual C++ Team Blog introduced a // solution, but it is complicated: // http://go.microsoft.com/?linkid=9729423. // The recommended way of calling native C++ class from .NET are // 1) use a C++/CLI class library to wrap the native C++ module, // and your .NET code class the C++/CLI wrapper class to // indirectly access the native C++ class. // 2) convert the native C++ module to be a COM server and expose // the native C++ class through a COM interface. Then, the // .NET code can access the class through .NET-COM interop. // Unload the DLL by calling GetModuleHandle and FreeLibrary. if (!FreeLibrary(GetModuleHandle(moduleName))) { Console.WriteLine("FreeLibrary failed w/err {0}", Marshal.GetLastWin32Error()); } // Check whether or not the module is loaded. isLoaded = IsModuleLoaded(moduleName); Console.WriteLine("Module \"{0}\" is {1}loaded", moduleName, isLoaded ? "" : "not "); }
public static IComparer GetComparer(CompareCallback innerComparer) { return new EntryComparer(innerComparer); }
public static extern int sqlite3_create_collation(IntPtr db, byte[] strName, int nType, IntPtr pvUser, CompareCallback func);
public static extern int Max(int a, int b, CompareCallback cmpFunc);
public static extern int CompareInts(int a, int b, CompareCallback cmpFunc);
static void Main(string[] args) { bool isLoaded = false; const string moduleName = "CppDynamicLinkLibrary"; // Check whether or not the module is loaded. isLoaded = IsModuleLoaded(moduleName); Console.WriteLine("Module \"{0}\" is {1}loaded", moduleName, isLoaded ? "" : "not "); // Load the DLL module. Console.WriteLine("Load the library"); using (UnmanagedLibrary lib = new UnmanagedLibrary(moduleName)) { // Check whether or not the module is loaded. isLoaded = IsModuleLoaded(moduleName); Console.WriteLine("Module \"{0}\" is {1}loaded", moduleName, isLoaded ? "" : "not "); // // Access the global data exported from the module. // // The solution does not allow you to access the global data // exported from a DLL module. // // Call the functions exported from the module. // string str = "HelloWorld"; int length; // Call int /*__cdecl*/ GetStringLength1(PWSTR pszString); GetStringLength1Delegate GetStringLength1 = lib.GetUnmanagedFunction <GetStringLength1Delegate>( "GetStringLength1"); if (GetStringLength1 == null) { throw new EntryPointNotFoundException( "Unable to find an entry point named 'GetStringLength1'"); } length = GetStringLength1(str); Console.WriteLine("GetStringLength1(\"{0}\") => {1}", str, length); // Call int __stdcall GetStringLength2(PWSTR pszString); GetStringLength2Delegate GetStringLength2 = lib.GetUnmanagedFunction <GetStringLength2Delegate>( "_GetStringLength2@4"); if (GetStringLength2 == null) { throw new EntryPointNotFoundException( "Unable to find an entry point named 'GetStringLength2'"); } length = GetStringLength2(str); Console.WriteLine("GetStringLength2(\"{0}\") => {1}", str, length); // // Call the callback functions exported from the module. // CompareCallback cmpFunc = new CompareCallback(CompareInts); MaxDelegate Max = lib.GetUnmanagedFunction <MaxDelegate>("Max"); if (Max == null) { throw new EntryPointNotFoundException( "Unable to find an entry point named 'Max'"); } int max = Max(2, 3, cmpFunc); Console.WriteLine("Function: Max(2, 3) => {0}", max); // // Use the class exported from a module. // // The solution does not allow you to use the class exported // from the DLL. // Attempt to free the library on exit. Console.WriteLine("Unload the dynamically-loaded DLL"); } // The DLL module should be unloaded here. // Check whether or not the module is loaded. isLoaded = IsModuleLoaded(moduleName); Console.WriteLine("Module \"{0}\" is {1}loaded", moduleName, isLoaded ? "" : "not "); }