是否有可能交换的C函数? [英] Is it possible to swap C functions?

查看:127
本文介绍了是否有可能交换的C函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想看看是否有人知道,如果可能交换C函数...?

Looking to see if anyone knows if its possible to swap C functions...?

 void swap2(int(*a)(int), int(*b)(int)) {
   int(*temp)(int) = a;
   *a = *b;
   *b = temp;
   // Gives 'Non-object type 'int (int)' is not assignable
 }

 swap2(&funcA, &funcB);

修改

更多的数据 - 一些答案已提供低于的工作,如使用创建功能PTR 的typedef ,指点它们的功能和开关的,它可以让你成功地调用新的交换师生比。

More data here as to intention -- Some answers have been provided below which do work such as creating the function ptr using typedef, pointing them to the functions and switching those, which lets you invoke the new swapped ptrs successfully.

的调用其原来的名称的功能交换显示无变化。基本上我正在寻找等价的C的objc调酒的。

BUT calling the functions by their original names after swapping shows no change. Essentially I'm looking for a c equivalent of the objc "swizzle".

我开始认为这是不可能的,因为C中的完全缺乏反思,并需要实际修改二进制文件本身(显然是不可行的)。 D:

I'm beginning to think this isn't possible, due to c's complete lack of reflection, and would require actually modifying the binary itself (obviously not feasible). D:

欢迎评论。

推荐答案

如果您使用的函数指针像下面,这是肯定的。

If you use the function pointers like below, it is yes

typedef int (*func_pt)(int);

func_pt a, b;

void swap(func_pt * a, func_pt * b)
{
    func_pt tmp = *b;
    *b = *a;
    *a = tmp;
}

swap(&a, &b);

或者你使用它,因为这,我认为这是否定的:

Or you use it as this, I think it is no:

int test1(int a)
{
    return a;
}

int test2(int b)
{
    return b;
}

swap(&test1, &test2);

完成编译工作程序

Complete compiling working program

#include <stdio.h>
#include <stdlib.h>

typedef int (* func_pt)(int);

func_pt a, b;

int test1(int a)
{
    printf("test1\n");
    return 1;
}

int test2(int a)
{
    printf("test2\n");
    return 2;
}

void swap(func_pt * a, func_pt * b)
{
    func_pt tmp = *b;

    *b = *a;
    *a = tmp;
}

int main(void)
{
    a = &test1;
    b = &test2;

    printf("before\n");
    a(1);
    b(1);

    swap(&a, &b);

    printf("after\n");
    a(1);
    b(2);

    return 0;

}

输出:

before
test1
test2
after
test2
test1

有些人不自己试试吧,只是说这absurd.So我给你一个例子。

Some people do not try it by themselves, just say it absurd.So I give you a example.

这篇关于是否有可能交换的C函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆