我正在尝试使用包装函数从 c
文件访问 C++
函数 (f1) 和字符串 a。代码如下。
抛出的错误是
Error : error: ‘p’ was not declared in this scope double d = f11( p,i);
1.h
double f11(struct c* p, int i);
1.cpp
#include<iostream>
using namespace std;
class c
{
public: double f1(int i) // how can i access from c
{
cout<<"I am in c++";
}
public : string a; // how can i access string from c
};
extern "C" double f11(c* p, int i) // wrapper function
{
return p->f1(i);
}
2.c
#include<stdio.h>
#include "1.h"
int main()
{
int i=9;
double d = f11( p,i);
}
最佳答案
如果您在 main.cpp 中手动包含“1.h”的内容,它将如下所示:
#include <stdio.h>
double f11(struct c* p, int i);
int main()
{
int i=9;
double d = f11( p,i);
}
那里有几个问题。
在调用
f11
之前,您尚未声明p
。您无法在
main
中构造类型为struct c
的对象。即使您通过提供struct c
和p
的声明来修复编译器错误,您也会遇到运行时问题,因为初始化p 的唯一方法
将其初始化为NULL。那对你没有任何好处,因为你有一条线return p->f1(i);
在
f11
中。f11
的声明和定义将导致链接器错误。如果您想将函数实现为extern "C"
,您还必须将其声明为extern "C"
。extern "C" double f11(c* p, int i);
在1.cpp中,成员函数
f1
不返回double。如果编译器没有将其报告为错误,这就是未定义错误的原因。
请参阅 http://ideone.com/aVFWFJ 处的工作代码.请注意,我更改了 c::f1
的实现,因此它不会崩溃。
关于c++ - 抛出错误 "as ‘p’ 中的包装函数未在此范围内声明”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32063360/