C#和c++之间相互传递函数指针

在C++和C#之中都有很多callback method,可以相互调用吗,怎么传递,是我表弟的问题.

1.定义c++ dll ,导出方法

// sort.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"
#include "sort.h"
#include "stdlib.h"
#include "iostream"
// 这是导出函数的一个示例。
typedef int (__cdecl *compare )(const void *elem1, const void *elem2 ) ;
void fnsort(int arr[],int size,compare fuccsharp)
{
std::cout<<"\r\narray length:"<<size<<"\r\n";
std::cout << "entry fnsort in cpp\r\n";
for(int index=0; index<size;index++){
std::cout << arr[index] << " ";
}
qsort(arr,size,sizeof(int),fuccsharp);
std::cout<<"\r\n sort end\r\n";
for(int index=0; index<size;index++){
std::cout << arr[index] << " ";
}
return ;
}

定义导出文件sort.def

LIBRARY   BTREE

EXPORTS
   fnsort

现在我们期待c#能呼叫fnsort,并实现funccsharp来实现排序算法,在c#中LoadLibrary,GetProcAddress,FreeLibrary当然是必不可少的.另外定义接口实现compare ,传入两个const void *,传出int

static int SortASC(IntPtr a, IntPtr b) {
int va = System.Runtime.InteropServices.Marshal.ReadInt32(a);
int vb = System.Runtime.InteropServices.Marshal.ReadInt32(b);
return va - vb;
}
static int SortDESC(IntPtr a, IntPtr b)
{
int va = System.Runtime.InteropServices.Marshal.ReadInt32(a);
int vb = System.Runtime.InteropServices.Marshal.ReadInt32(b);
return vb - va;
}

同时定义委托

[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
public delegate int INTARRAYSORT(IntPtr a, IntPtr b);

现在我们认为我们实现了int (__cdecl *compare )(const void *elem1, const void *elem2 ) ;现在没事了,一切顺利了,Marshal.GetDelegateForFunctionPointer会将一个intptr转换为一个委托 ,new delegate(pfunc)可以将一个csharp func转换为一个函数指针传绘cpp,依上例,完整实现

using System;
using System.Text;
using System.Runtime.InteropServices; namespace callDLL
{
    class Program
    {
        [DllImport("kernel32")]
        public static extern IntPtr LoadLibrary(string lpFileName);
        [DllImport("Kernel32")]
        public static extern bool FreeLibrary(IntPtr handle);
        [DllImport("Kernel32")]
        public static extern IntPtr GetProcAddress(IntPtr handle, String funcname);         [UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
        public delegate int INTARRAYSORT(IntPtr a, IntPtr b);
        [UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
        public delegate void CPPSORT(int[] arr, int size, INTARRAYSORT callback);         static int SortASC(IntPtr a, IntPtr b) {
            int va = System.Runtime.InteropServices.Marshal.ReadInt32(a);
            int vb = System.Runtime.InteropServices.Marshal.ReadInt32(b);
            return va - vb;
        }
        static int SortDESC(IntPtr a, IntPtr b)
        {
            int va = System.Runtime.InteropServices.Marshal.ReadInt32(a);
            int vb = System.Runtime.InteropServices.Marshal.ReadInt32(b);
            return vb - va;
        }
        static void Main(string[] args)
        {
            IntPtr dll = LoadLibrary("sort.dll");
            IntPtr func=GetProcAddress(dll, "fnsort");
            CPPSORT cppsort = (CPPSORT)Marshal.GetDelegateForFunctionPointer(func, typeof(CPPSORT));
            int[] arr = new int[] { 1, 7, 4 };
            //回叫函数可以使用委托实现
            cppsort(arr,arr.Length,new INTARRAYSORT(SortASC));
            cppsort(arr, arr.Length, new INTARRAYSORT(SortDESC));
            FreeLibrary(dll);
            Console.WriteLine("\r\nend");
            Console.Read();
        }
    }
}

输出如下


array length:3

entry fnsort in cpp

1 7 4

 sort end

1 4 7

array length:3

entry fnsort in cpp

1 4 7

 sort end

7 4 1

end

C# c++ 传递函数指针的更多相关文章

  1. C++传递函数指针

    函数指针是一个很好的类型.因此,您可以编写一个函数,它的一个参数是一个函数指针.然后.在(外部)当函数使用的函数指针参数,来间接调用时调用相应的参数的函数的函数. 因为指针在不同的情况下能够指向不同的 ...

  2. delphi 中的函数指针 回调函数(传递函数指针,以及它需要的函数参数)

    以下代码仅仅是测试代码:delphi XE7 UP1 interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.V ...

  3. 《笨办法学C》笔记之指针

    C语言编程主要操作的对象就是指针. 指针从哪里来 指针就是表示内存存储区域的一组数值,使用%p格式化字符串. Linux系统会为程序维护两个临时变量存储位置:栈.堆.栈的空间少,栈通常在用户更高的地址 ...

  4. 深入理解C指针之三:指针和函数

    原文:深入理解C指针之三:指针和函数 理解函数和指针的结合使用,需要理解程序栈.大部分现代的块结构语言,比如C,都用到了程序栈来支持函数的运行.调用函数时,会创建函数的栈帧并将其推到程序栈上.函数返回 ...

  5. C语言函数指针的使用

    使用函数指针时一定要注意,因为c不会检查参数是否正确 区分返回指针的函数和函数指针 int *f4();返回一个整数指针 int (*f5)();返回整数的函数指针 int * (*f6)();返回整 ...

  6. 《深入理解C指针》

    <深入理解C指针> 基本信息 原书名:Understanding and using C pointers 作者: (美)Richard Reese 译者: 陈晓亮 丛书名: 图灵程序设计 ...

  7. 深入理解C指针----学习笔记

      深入理解C指针     第1章 认识指针   理解指针的关键在于理解C程序如何管理内存,指针包含的就是内存地址.     1.1 指针和内存   C程序在编译后,以三种方式使用内存: 1. 静态. ...

  8. C指针的这些使用技巧,掌握后立刻提升一个Level

    这是道哥的第016篇原创 关注+星标公众号,不错过最新文章 目录 一.前言 二.八个示例 1. 开胃菜:修改主调函数中的数据 2. 在被调用函数中,分配系统资源 2.1 错误用法 2.2 正确用法 3 ...

  9. C#与C/C++的交互zz

    C#与C++交互,总体来说可以有两种方法: 利用C++/CLI作为代理中间层 利用PInvoke实现直接调用 第一种方法:实现起来比较简单直观,并且可以实现C#调用C++所写的类,但是问题是MONO构 ...

随机推荐

  1. Sqlite出现SQL error: database disk image is malformed的处理

    SQLite有一个很严重的缺点就是不提供Repair命令.导致死亡提示database disk image is malformed它的产生有很多种可能,比如,磁盘空间不足,还有就是写入数据过程中突 ...

  2. HTML5的本地存储功能,值得研究

    https://developer.chrome.com/apps/offline_storage 搜索“chrome html5 本地缓存”,一大堆文章,比如: http://www.cnblogs ...

  3. 一个ShellExecute的超全说明(www.phidels.com这个网站很多内容)

    I. Introduction / Déclaration ShellExecute fait partie des innombrables fonctions de l'API Windows ; ...

  4. hibernate的配置 1

    hibernate 是一种ORM框架,是ORM框架中一个典范 ORM叫做对象关系映射 是面向对象语言和关系型数据库之间的映射关系 所以只有在面向对象语言或者关系型数据库没用的时候ORM才会消失 ORM ...

  5. DIOR HOMME_百度百科

    DIOR HOMME_百度百科     DIOR HOMME    编辑    Dior Homme 男装品牌,中文名迪奥·桀傲,由迪奥 (Dior) 在2001年更名更来,品牌来源地法国.迪奥·桀傲 ...

  6. 从零开始学C++之IO流类库(四):输出流格式化(以操纵子方式格式化 以ios类成员函数方式格式化)

    一.以操纵子方式格式化 数据输入输出的格式控制使用系统头文件<iomanip>中提供的操纵符.把它们作为插入操作符<<的输出对象即可.如setiosflags.setw.set ...

  7. asp.net中MVC多语言包的使用

    Global.asax.cs文件 protected void Application_AcquireRequestState(object sender, EventArgs e) { if (Ht ...

  8. C#_会员管理系统:开发六(数据搜索)

    增加界面中的搜索功能 会员资料管理界面(VIPManager.cs): 详细代码如下: using System; using System.Collections.Generic; using Sy ...

  9. Oracle AWR 报告详解

    转自:http://blog.csdn.net/laoshangxyc/article/details/8615187 持续更新中... Oracle awr报告详解 DB Name DB Id In ...

  10. 语法糖----JAVA

    语法糖 语法糖(Syntactic Sugar),也叫糖衣语法,是英国计算机科学家彼得·约翰·兰达(Peter J. Landin)发明的一个术语.指的是,在计算机语言中添加某种语法,这种语法能使程序 ...