(ת)ʹÓÃC/C++À©Õ¹Python
ʹÓÃC/C++À©Õ¹Python
·Òë:
gashero
Èç¹ûÄã»áÓÃC£¬ÊµÏÖPythonǶÈëÄ£¿éºÜ¼òµ¥¡£ÀûÓÃÀ©Õ¹Ä£¿é¿É×öºÜ¶àPython²»·½±ã×öµÄÊÂÇ飬ËûÃÇ¿ÉÒÔÖ±½Óµ÷ÓÃC¿âºÍϵͳµ÷Óá£
ΪÁËÖ§³ÖÀ©Õ¹£¬Python API¶¨ÒåÁËһϵÁк¯Êý¡¢ºêºÍ±äÁ¿£¬ÌṩÁ˶ÔPythonÔËÐÐʱϵͳµÄ·ÃÎÊÖ§³Ö¡£PythonµÄC APIÓÉCÔ´Âë×é³É£¬²¢°üº¬ “Python.h” Í·Îļþ¡£
±àдÀ©Õ¹Ä£¿éÓëÄãµÄϵͳÏà¹Ø£¬ÏÂÃæ»áÏê½â¡£
Ŀ¼
1 Ò»¸ö¼òµ¥µÄÀý×Ó
2 ¹ØÓÚ´íÎóºÍÒì³£
3 »Øµ½Àý×Ó
4 Ä£¿é·½·¨±íºÍ³õʼ»¯º¯Êý
5 ±àÒëºÍÁ¬½Ó
6 ÔÚCÖе÷ÓÃPythonº¯Êý
7 ½âÎö´«¸øÀ©Õ¹Ä£¿éº¯ÊýµÄ²ÎÊý
8 ½âÎö´«¸øÀ©Õ¹Ä£¿éº¯ÊýµÄ¹Ø¼ü×Ö²ÎÊý
9 ¹¹ÔìÈÎÒâÖµ
10 ÒýÓüÆÊý
10.1 PythonÖеÄÒýÓüÆÊý
10.2 ÓµÓйæÔò
10.3 ΣÏյı¡±ù
10.4 NULLÖ¸Õë
11 ʹÓÃC++±àдÀ©Õ¹
12 Ìṩ¸øÆäËûÄ£¿éÒÔC API
1 Ò»¸ö¼òµ¥µÄÀý×Ó
ÏÂÃæµÄÀý×Ó´´½¨Ò»¸ö½Ð×ö “spam” µÄÀ©Õ¹Ä£¿é£¬µ÷ÓÃC¿âº¯Êý system() ¡£Õâ¸öº¯ÊýÊäÈëÒ»¸öNULL½áβµÄ×Ö·û´®²¢·µ»ØÕûÊý£¬¿É¹©Pythonµ÷Ó÷½Ê½ÈçÏÂ:
>>> import spam
>>> status=spam.system("ls -l")
Ò»¸öCÀ©Õ¹Ä£¿éµÄÎļþÃû¿ÉÒÔÖ±½ÓÊÇ Ä£¿éÃû.c »òÕßÊÇ Ä£¿éÃûmodule.c ¡£µÚÒ»ÐÐÓ¦¸Ãµ¼ÈëÍ·Îļþ:
#include <Python.h>
Õâ»áµ¼ÈëPython API¡£
Warning
ÒòΪPythonº¬ÓÐһЩԤ´¦Àí¶¨Ò壬ËùÒÔÄã±ØÐëÔÚËùÓзDZê׼ͷÎļþµ¼Èë֮ǰµ¼ÈëPython.h ¡£
Python.hÖÐËùÓÐÓû§¿É¼ûµÄ·ûºÅ¶¼ÓÐ Py »ò PY µÄǰ׺£¬³ý·Ç¶¨ÒåÔÚ±ê׼ͷÎļþÖС£ÎªÁË·½±ã “Python.h” Ò²°üº¬ÁËһЩ³£Óõıê׼ͷÎļþ£¬°üÀ¨<stdio.h>£¬<string.h>£¬<errno.h>£¬<stdlib.h>¡£Èç¹ûÄãµÄϵͳûÓкóÃæµÄÍ·Îļþ£¬Ôò»áÖ±½Ó¶¨Ò庯Êý malloc() ¡¢ free() ºÍ realloc() ¡£
ÏÂÃæÌí¼ÓC´úÂëµ½À©Õ¹Ä£¿é£¬µ±µ÷Óà “spam.system(string)” ʱ»á×ö³öÏìÓ¦:
static PyObject*
spam_system(PyObject* self, PyObject* args) {
const char* command;
int sts;
if (!PyArg_ParseTuple(args,"s",&command))
return NULL;
sts=system(command
Ïà¹ØÎĵµ£º
ACE×ÔÊÊÅäͨÐÅ»·¾³£¨ADAPTIVE Communication Environment£©ÊÇ¿ÉÒÔ×ÔÓÉʹÓᢿª·ÅÔ´ÂëµÄÃæÏò¶ÔÏó£¨OO£©¿ò¼Ü£¨Framework£©£¬ÔÚÆäÖÐʵÏÖÁËÐí¶àÓÃÓÚ²¢·¢Í¨ÐÅÈí¼þµÄºËÐÄģʽ¡£ACEÌṩÁËÒ»×é·á¸»µÄ¿É¸´ÓÃC++ Wrapper Facade£¨°ü×°Íâ¹Û£©ºÍ¿ò¼Ü×é¼þ£¬¿É¿çÔ½¶àÖÖƽ̨Íê³ÉͨÓõÄͨÐÅÈí¼þÈÎÎñ£¬ÆäÖаüÀ¨£ºÊ¼þ¶à··ÖÀëºÍʼþ´¦À ......
¶þ·Ö²éÕҵĴúÂë.
int bfind(int* a,int len,int val)
{
int m = len/2;
int l = 0;
int r = len;
while(l!=m && r!= m)
{
if(a[m] > val)
& ......
1£®ÒÑÖªstrcpy º¯ÊýµÄÔÐÍÊÇ£º
char *strcpy(char *strDest, const char *strSrc);
ÆäÖÐstrDest ÊÇÄ¿µÄ×Ö·û´®£¬strSrc ÊÇÔ´×Ö·û´®¡£²»µ÷ÓÃC++/C µÄ×Ö·û´®¿âº¯Êý£¬Çë±àдº¯Êý strcpy
´ð°¸£º
char *strcpy(char *strDest, const char *strSrc)
{
if ( strDest == NULL || strSrc == NULL)
return NULL ;
if ( strDest ......
²Ù×÷ϵͳµÄÒ»¸ö¾µäÎÊÌâÊÇ"Éú²úÕß-Ïû·ÑÕß"ÎÊÌâ, ÕâÉ漰ͬ²½ÐźÅÁ¿ºÍ»¥³âÐźÅÁ¿µÄÓ¦ÓÃ, ÔÚÕâÀï,ÎÒÓÃÏ̵߳Äͬ²½ºÍ»¥³âÀ´ÊµÏÖ.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define N 2 // Ïû·ÑÕß» ......
C³ÌÐòÖоßÓзḻµÄÊý¾ÝÀàÐÍ£¬°üÀ¨ÉùÃ÷ÖÐÏÔʽ¶¨ÒåµÄÀàÐͺÍÓÃ×ö±í´ïʽÖмäÀàÐ͵ĵ¼³öÀàÐÍ¡£ÀýÈ磬ÏÂÃæµÄ¸³ÖµÓï¾ä°üº¬3 ÖÖ²»Í¬ÀàÐÍ:
int *p, x;
*p = x;
xÊÇÒ»¸ö´æ·ÅÕûÊýµÄµ¥ÔªµÄµØÖ·£¬Òò´ËxµÄµØÖ·µÄÀàÐÍÊÇ£ºÖ¸ÏòÒ»¸öÕûÊýµÄÖ¸Õë¡£xµÄÖµµÄÀàÐÍÊÇÕûÐÍ¡£Í¬Ñù, pµÄ×óÖµµÄÀàÐÍÊÇÖ¸ÏòÒ»¸öÕ ......