c++demo发新浪微博图片

来源:互联网 发布:张艺兴真傻量身高 知乎 编辑:程序博客网 时间:2024/04/28 09:56

keyword:vs2015,新浪微博,python

要做一个c++的图片处理的桌面程序的课程作业,分享功能要分享到新浪微博之类的。本文是一个 用轮子的(雾)。c++中调用python。

vs2015 python2.7.12 c++

背景
要调用新浪微博的各种功能,大概两种方式:有新浪提供的API(代码有点多),编程语言对应的SDK。
我选的是python的新浪微博的SDK,这个SDK是python2.x的。python3.x不行的样子。
c++的SDK不支持OAuth2.0(大概是这个问题?)
python下的新浪微博的SDK是用OAuth2.0,所以要:

  • 进入网页,获取授权

  • 得到access_token, expires_in(这个授权的时限)

link1:用python发新浪微博
这个链接写的比较精简,但是重要的步骤都在


c++和python的混合编译
link2:这个写的 链接最详细
上文的链接写的十分详细,非常感谢他。
我一开始用的是vs2013出现了蛮多问题的。python2.7.12。

  • 缺少python27_d.lib 我选择release下运行

  • 定义冲突math release下运行

  • 注意python版本是32位的在32位环境下,64位的在64位下

这是我遇到的问题,具体方法第二个链接有详细的步骤。
python代码

#encoding=utf-8import weibo   APP_KEY = 'xxxx'  APP_SECRET = 'xxxxxx'  CALL_BACK = 'https://api.weibo.com/oauth2/default.htm'code = ' 'def run(a,b):    client = weibo.APIClient(APP_KEY, APP_SECRET, CALL_BACK)      auth_url = client.get_authorize_url()      print ("auth_url : " + auth_url)    '''    if not access_token:        try:            client.set_access_token(r.access_token, r.expires_in)        except error:    '''    file_object = open('data.txt')    list_of_all_the_lines = file_object.readlines( )    access_token=list_of_all_the_lines[0]    expires_in=list_of_all_the_lines[1]    client.set_access_token(access_token.strip(), int(expires_in))    content=a    fileadr=b    f=open(b,'rb')    client.statuses.upload.post(status=content, pic=f)    f.close()if __name__ == "__main__":      run('test','E:\\test_C_py\\1.jpg')

这部分代码可以直接运行,功能只有把一个指定路径和文字发到微博上。在c++代码中调用run这个函数

c++代码

#include <Python.h>#include <iostream>  #include <string>  void printDict(PyObject* obj) {    if (!PyDict_Check(obj))        return;    PyObject *k, *keys;    keys = PyDict_Keys(obj);    for (int i = 0; i < PyList_GET_SIZE(keys); i++) {        k = PyList_GET_ITEM(keys, i);        char* c_name = PyString_AsString(k);        printf("%s\n", c_name);    }}int main() {    Py_Initialize();    if (!Py_IsInitialized())        return -1;    PyRun_SimpleString("import sys");    PyRun_SimpleString("import weibo");    PyRun_SimpleString("sys.path.append('./')");    //导入模块      PyObject* pModule = PyImport_ImportModule("testFuck");    if (!pModule) {        printf("Cant open python file!\n");        return -1;    }    //模块的字典列表      PyObject* pDict = PyModule_GetDict(pModule);    if (!pDict) {        printf("Cant find dictionary.\n");        return -1;    }    PyObject *pArgs;    pArgs = PyTuple_New(2);    PyTuple_SetItem(pArgs, 0, Py_BuildValue("s","in vs2015 with python"));    PyTuple_SetItem(pArgs, 1, Py_BuildValue("s","E:\\test_C_py\\testNew\\testDemo\\testDemo\\1.jpg" ));    //打印出来看一下      printDict(pDict);    //演示函数调用      PyObject* pFunHi = PyDict_GetItemString(pDict, "run");    PyObject_CallObject(pFunHi, pArgs);    Py_DECREF(pFunHi);    Py_DECREF(pModule);    Py_Finalize();    return 0;}

demo里面就只有这个cpp文件,将.py和.cpp放在同一个目录里,在vs中用release下运行。

结果图

0 0
原创粉丝点击