免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2606 | 回复: 1
打印 上一主题 下一主题

C++中调用python函数失败,不知道如何搞,大家帮忙 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-09-08 08:48 |只看该作者 |倒序浏览
在C++为主的程序框架中调用python函数失败,不知道是什么原因


但是我在做计算的时候要调用numpy,同样一个sin函数
    print("math.sin = %f" % math.sin(3.14))
    print("numpy.sin = %f" % numpy.sin(3.14))
第二句死活异常,报的错是类型异常,

主要是第三方库的问题,但没有找到解决问题的办法。不知道如何搞,大家帮忙
如果调用的是函数中调用的都是标准库模块的好像没有什么问题。


下面是代码:

/////////////////////////////////////////////////////////////////////////////////////
python代码(python2.72)
hellomod.py

# -*- coding: utf-8 -*-

import os
import string
import math
import numpy

def c2python(name):
    print("python out,hello %s" %name)

def python2c(a,b):
    r1=a+b
    r2 = os.getcwd()
    return (r1,r2)

def mypdf0(a):
    print(string.upper(a))
    print("math.sin = %f" % math.sin(3.14))
    print("numpy.sin = %f" % numpy.sin(3.14))
    return math.sin(3.14)

if __name__ == "__main__":
    mypdf0(3.14)
/////////////////////////////////////////////////////////////////////////////////////
C代码(vc6)

#include "StdAfx.h"
#include "wtypes.h"
#include "winbase.h"
#include "cstdio"
#include "cstdlib"
#include "stdafx.h"
#include "iostream"
#include "algorithm"
#include "Python.h"

int main(int argc, char* argv[])
{
    char format[1024];
    char path[256];
    using namespace std;
    int result = -1;

    Py_Initialize();   
    if (!Py_IsInitialized())  
        return -1;  

    result = PyRun_SimpleStringFlags("import sys",NULL);
    ::GetCurrentDirectory(256,(LPTSTR)path);
    sprintf(format,"sys.path.append('%s')",path);
    result = PyRun_SimpleStringFlags(format,NULL);
    result = PyRun_SimpleStringFlags("sys.path.append('./')",NULL);

    PyObject* pModule = PyImport_ImportModule("hellomod");   
    if (!pModule)
    {   
        cout<<"导入模块失败!\n"<<endl;   
        return -1;   
    }

    PyObject* pFunHi = PyObject_GetAttrString(pModule, "mypdf0");
    if (!pFunHi || !PyCallable_Check(pFunHi))
    {//检查函数是否可以被调用
        cout<<"函数mypdf0未找到!\n"<<endl;
        return -1;
    }
   
    PyObject* pargs = PyTuple_New(1);//多个就构造多个
    PyTuple_SetItem(pargs, 0, Py_BuildValue("s","abc"));
    PyObject* okfun = PyObject_CallObject(pFunHi, pargs);

    if (!okfun)
    {
        char* error = PyString_AsString(PyObject_Str(PyErr_Occurred()));
        cout << error << endl;
    }

    Py_DECREF(pFunHi);
    Py_DECREF(pargs);
    Py_DECREF(pModule);   
    Py_Finalize();   
    return 0;   
}
/////////////////////////////////////////////////////////////////////////////////////

论坛徽章:
0
2 [报告]
发表于 2012-09-09 11:17 |只看该作者
完美解决,python & C++双枪将。完美组合。太美妙了。、

解决原因:多字节惹的祸哈。注意编辑器的使用啊,害死人的。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP