请问,在.c文件中能不能直接调用.cpp中定义类的方法

时间:2022-09-30 16:40:43
请问,在.c文件中能不能直接调用.cpp中定义类的方法。
因为,有些c文件中想调用cpp中定义的类的方法。

10 个解决方案

#1


只要在包含相关头,理论上来说应该可以的

#2


可能不行吧,C根本就没有类这个东东嘛。

#3


可能跟编译器有关系吧  c的文件用cpp编译器编译也许就行

#4


C++会对函数进行名字编码

#5




把c++封裝成dll
其它的估計不行.

#6


将.c文件改为.cpp

#7


可以调用,
不过你调用是需加类名,需这样调用:form2->pixmapLabel2_3_2->hide();//form2是个类

#8


即使加类名,那个类没有实例化,你怎么调。所以你只能调类中的static函数。

#9


你的.cpp用c编就可以了

#10


如何用c语言调用c++做成的动态链接库:

链接库头文件:
//head.h
class A
{
        public:
        A();
        virtual ~A();
        int gt();
        int pt();
private:
        int s;
};

.cpp
//firstso.cpp
#include <iostream> 
#include "head.h"

A::A(){}
A::~A(){}
int A::gt()
        {
s=10;
                }
int A::pt()
        {
        
                std::cout<<s<<std::endl;
        }
编译命令如下:
g++ -shared -o libmy.so firstso.cpp
这时候生成libmy.so文件,将其拷贝到系统库里面:/usr/lib/
进行二次封装:
.cpp
//secso.cpp
#include <iostream>
#include "head.h"
extern "C" 
{
 int f();
 int f()
 {
  A a;
  a.gt();
  a.pt();
  return 0;
 }
}

编译命令:
gcc -shared -o sec.so secso.cpp -L. -lmy
这时候生成第二个.so文件,此时库从一个类变成了一个c的接口.
拷贝到/usr/lib
下面开始调用:
//test.c
#include "stdio.h"
#include "dlfcn.h"

#define SOFILE "sec.so"
int (*f)();
int main()
{
void *dp;
dp=dlopen(SOFILE,RTLD_LAZY);
f=dlsym(dp,"f");
f();
return 0;
}
编译命令如下:
gcc -rdynamic -s -o myapp test.c
运行Z$./myapp
10
$


源作者Blog:http://blog.csdn.net/playmud/

#1


只要在包含相关头,理论上来说应该可以的

#2


可能不行吧,C根本就没有类这个东东嘛。

#3


可能跟编译器有关系吧  c的文件用cpp编译器编译也许就行

#4


C++会对函数进行名字编码

#5




把c++封裝成dll
其它的估計不行.

#6


将.c文件改为.cpp

#7


可以调用,
不过你调用是需加类名,需这样调用:form2->pixmapLabel2_3_2->hide();//form2是个类

#8


即使加类名,那个类没有实例化,你怎么调。所以你只能调类中的static函数。

#9


你的.cpp用c编就可以了

#10


如何用c语言调用c++做成的动态链接库:

链接库头文件:
//head.h
class A
{
        public:
        A();
        virtual ~A();
        int gt();
        int pt();
private:
        int s;
};

.cpp
//firstso.cpp
#include <iostream> 
#include "head.h"

A::A(){}
A::~A(){}
int A::gt()
        {
s=10;
                }
int A::pt()
        {
        
                std::cout<<s<<std::endl;
        }
编译命令如下:
g++ -shared -o libmy.so firstso.cpp
这时候生成libmy.so文件,将其拷贝到系统库里面:/usr/lib/
进行二次封装:
.cpp
//secso.cpp
#include <iostream>
#include "head.h"
extern "C" 
{
 int f();
 int f()
 {
  A a;
  a.gt();
  a.pt();
  return 0;
 }
}

编译命令:
gcc -shared -o sec.so secso.cpp -L. -lmy
这时候生成第二个.so文件,此时库从一个类变成了一个c的接口.
拷贝到/usr/lib
下面开始调用:
//test.c
#include "stdio.h"
#include "dlfcn.h"

#define SOFILE "sec.so"
int (*f)();
int main()
{
void *dp;
dp=dlopen(SOFILE,RTLD_LAZY);
f=dlsym(dp,"f");
f();
return 0;
}
编译命令如下:
gcc -rdynamic -s -o myapp test.c
运行Z$./myapp
10
$


源作者Blog:http://blog.csdn.net/playmud/