【问题标题】:Error while Passing function pointer as parameter将函数指针作为参数传递时出错
【发布时间】:2016-11-16 14:34:06
【问题描述】:

我有一个程序将调用库中存在的函数。函数的参数是一个函数指针。

Helloworld.c

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include "helloworld.h"

struct data_buffer
   {
        char name[10];
   }data;

int main()
  {
     int result; 

     int (*func_pointer)(&data_buffer); //function pointer which takes structure as parameter

      result=send_data(func_ponter); //error

      func_pointer(&data_buffer);  //call the SPI write

  }

helloworld.h

#ifndef HELLOWORLD_H
#define HELLOWORLD_H

/* Some cross-platform definitions generated by autotools */
#if HAVE_CONFIG_H
#  include <config.h>
#endif /* HAVE_CONFIG_H */
/*
 * Example function
 */

struct data_buffer;

extern int send_data(int (*func_pointer)(&data_buffer)); //is the declaration correct

#endif 

libexample.c

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


int send_data(int (*func_pointer)(&data_buffer)) //error 
{

func_pointer=spi_write();  // assigning the function pointer to SPI WRITE function
return;
}

所以我的项目目标是将函数指针作为参数发送到 send_data 函数。在库程序中,必须将函数指针分配给 spi_write() 函数,然后才能在 Helloworld 程序中借助函数指针调用 SPI_Write。

【问题讨论】:

  • 不太清楚您要达到的目标。将spi_write 分配给参数会完成什么?什么spi_write? (另外,当你写 x = y; 时,你是在“将 y 分配给 x”,而不是相反。)

标签: c pointers shared-libraries function-pointers


【解决方案1】:
extern int send_data(int (*func_pointer)(&data_buffer)); //is the declaration correct

函数的参数必须是类型。类型使用* 表示它是一个指针。所以&amp;data_buffer 在声明中是不正确的。

还要注意,在 C 中,与 C++ 不同,结构名称不是类型,您需要将其与关键字 struct 结合使用(或使用 typedef)。所以使用:

extern int send_data(int (*func_pointer)(struct data_buffer *));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-15
    • 2020-11-08
    • 2021-12-18
    • 2021-05-13
    • 1970-01-01
    • 2013-03-16
    • 2015-01-29
    • 1970-01-01
    相关资源
    最近更新 更多