本文整理汇总了C++中PyCallable_Check函数的典型用法代码示例。如果您正苦于以下问题:C++ PyCallable_Check函数的具体用法?C++ PyCallable_Check怎么用?C++ PyCallable_Check使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PyCallable_Check函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: Channel_tp_init
static int
Channel_tp_init(Channel *self, PyObject *args, PyObject *kwargs)
{
int r, flags, tries, ndots, tcp_port, udp_port, optmask, ndomains, socket_send_buffer_size, socket_receive_buffer_size;
char *lookups;
char **c_domains;
double timeout;
struct ares_options options;
PyObject *servers, *domains, *sock_state_cb;
static char *kwlist[] = {"flags", "timeout", "tries", "ndots", "tcp_port", "udp_port",
"servers", "domains", "lookups", "sock_state_cb", "socket_send_buffer_size", "socket_receive_buffer_size", NULL};
optmask = 0;
flags = tries = ndots = tcp_port = udp_port = socket_send_buffer_size = socket_receive_buffer_size = -1;
timeout = -1.0;
lookups = NULL;
c_domains = NULL;
servers = domains = sock_state_cb = NULL;
if (self->channel) {
PyErr_SetString(PyExc_AresError, "Object already initialized");
return -1;
}
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|idiiiiOOsOii:__init__", kwlist, &flags, &timeout, &tries, &ndots, &tcp_port, &udp_port, &servers,
&domains, &lookups, &sock_state_cb, &socket_send_buffer_size, &socket_receive_buffer_size)) {
return -1;
}
if (sock_state_cb && !PyCallable_Check(sock_state_cb)) {
PyErr_SetString(PyExc_TypeError, "sock_state_cb is not callable");
return -1;
}
r = ares_library_init(ARES_LIB_INIT_ALL);
if (r != ARES_SUCCESS) {
RAISE_ARES_EXCEPTION(r);
return -1;
}
self->lib_initialized = True;
memset(&options, 0, sizeof(struct ares_options));
if (flags != -1) {
options.flags = flags;
optmask |= ARES_OPT_FLAGS;
}
if (timeout != -1) {
options.timeout = (int)timeout * 1000;
optmask |= ARES_OPT_TIMEOUTMS;
}
if (tries != -1) {
options.tries = tries;
optmask |= ARES_OPT_TRIES;
}
if (ndots != -1) {
options.ndots = ndots;
optmask |= ARES_OPT_NDOTS;
}
if (tcp_port != -1) {
options.tcp_port = tcp_port;
optmask |= ARES_OPT_TCP_PORT;
}
if (udp_port != -1) {
options.udp_port = udp_port;
optmask |= ARES_OPT_UDP_PORT;
}
if (socket_send_buffer_size != -1) {
options.socket_send_buffer_size = socket_send_buffer_size;
optmask |= ARES_OPT_SOCK_SNDBUF;
}
if (socket_receive_buffer_size != -1) {
options.socket_receive_buffer_size = socket_receive_buffer_size;
optmask |= ARES_OPT_SOCK_RCVBUF;
}
if (sock_state_cb) {
options.sock_state_cb = ares__sock_state_cb;
options.sock_state_cb_data = (void *)self;
optmask |= ARES_OPT_SOCK_STATE_CB;
Py_INCREF(sock_state_cb);
self->sock_state_cb = sock_state_cb;
}
if (lookups) {
options.lookups = lookups;
optmask |= ARES_OPT_LOOKUPS;
}
if (domains) {
process_domains(domains, &c_domains, &ndomains);
if (ndomains == -1) {
goto error;
}
options.domains = c_domains;
options.ndomains = ndomains;
optmask |= ARES_OPT_DOMAINS;
}
r = ares_init_options(&self->channel, &options, optmask);
if (r != ARES_SUCCESS) {
RAISE_ARES_EXCEPTION(r);
//.........这里部分代码省略.........
开发者ID:aguinet,项目名称:pycares,代码行数:101,代码来源:cares.c
示例2: DNSResolver_func_getaddrinfo
static PyObject *
DNSResolver_func_getaddrinfo(DNSResolver *self, PyObject *args, PyObject *kwargs)
{
char *name;
char port_str[6];
int port, family, socktype, protocol, flags, r;
struct addrinfo hints;
ares_cb_data_t *cb_data = NULL;
uv_getaddrinfo_t* handle = NULL;
PyObject *callback;
static char *kwlist[] = {"callback", "name", "port", "family", "socktype", "protocol", "flags", NULL};
port = socktype = protocol = flags = 0;
family = AF_UNSPEC;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|iiiii:getaddrinfo", kwlist, &name, &callback, &port, &family, &socktype, &protocol, &flags)) {
return NULL;
}
if (!PyCallable_Check(callback)) {
PyErr_SetString(PyExc_TypeError, "a callable is required");
return NULL;
}
if (port < 0 || port > 65536) {
PyErr_SetString(PyExc_ValueError, "port must be between 0 and 65536");
return NULL;
}
snprintf(port_str, sizeof(port_str), "%d", port);
handle = PyMem_Malloc(sizeof(uv_getaddrinfo_t));
if (!handle) {
PyErr_NoMemory();
goto error;
}
cb_data = (ares_cb_data_t*) PyMem_Malloc(sizeof *cb_data);
if (!cb_data) {
PyErr_NoMemory();
goto error;
}
Py_INCREF(callback);
cb_data->resolver = self;
cb_data->cb = callback;
handle->data = (void *)cb_data;
memset(&hints, 0, sizeof(hints));
hints.ai_family = family;
hints.ai_socktype = socktype;
hints.ai_protocol = protocol;
hints.ai_flags = flags;
r = uv_getaddrinfo(UV_LOOP(self), handle, &getaddrinfo_cb, name, port_str, &hints);
if (r != 0) {
raise_uv_exception(self->loop, PyExc_DNSError);
goto error;
}
Py_RETURN_NONE;
error:
if (handle) {
PyMem_Free(handle);
}
if (cb_data) {
Py_DECREF(callback);
PyMem_Free(cb_data);
}
return NULL;
}
开发者ID:ikeikeikeike,项目名称:pyuv,代码行数:72,代码来源:dns.c
示例3: main
int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *pArgs;
if (argc < 5) {
printf("Usage: exe_name python_source function_name\n");
return 1;
}
/* Initialize the Python Interpreter */
Py_Initialize();
PySys_SetArgv(argc, argv);
/* Build the name object */
/* Convery C-String to PyString */
pName = PyString_FromString(argv[1]);
/* Load the module object */
pModule = PyImport_Import(pName);
/* pDict is a borrowed reference */
/* Equivalent to __dict__ attribute of object */
pDict = PyModule_GetDict(pModule);
/* pFunc is also a borrowed reference */
/* Get value of object with key 'argv[2]' */
/* This is the function we'll execute */
pFunc = PyDict_GetItemString(pDict, argv[2]);
/* Prepare a tuple which will contain arguments for our Python function */
/* Create tuple of size 2 */
pArgs = PyTuple_New(2);
/* We set the values at indices as provided by main program arguments */
PyTuple_SetItem(pArgs, 0, PyInt_FromLong(atoi(argv[3])));
PyTuple_SetItem(pArgs, 1, PyInt_FromLong(atoi(argv[4])));
/* First check if the PyObject retrieved is callable */
if (PyCallable_Check(pFunc)) {
/* To store return value by the called function */
PyObject *result;
/* => PyObject_CallObject(object, arguments) */
if (result = PyObject_CallObject(pFunc, pArgs)) {
/* We convery returned PyObject to C's long */
long resultLong = PyInt_AsLong(result);
printf("Result is: %ld\n", resultLong);
}
else {
/* Since NULL is returned, and NULL is error */
printf("Failed\n");
}
}
else {
/* What you provided wasnt callable */
PyErr_Print();
}
/* Clean up */
Py_DECREF(pModule);
Py_DECREF(pName);
Py_DECREF(pArgs);
/* Shutdown Python Interpreter */
Py_Finalize();
return 0;
}
开发者ID:vishesh,项目名称:pyconin-11,代码行数:69,代码来源:main.c
示例4: handle_gpi_callback
/**
* @name Callback Handling
* @brief Handle a callback coming from GPI
* @ingroup python_c_api
*
* GILState before calling: Unknown
*
* GILState after calling: Unknown
*
* Makes one call to TAKE_GIL and one call to DROP_GIL
*
* Returns 0 on success or 1 on a failure.
*
* Handles a callback from the simulator, all of which call this function.
*
* We extract the associated context and find the Python function (usually
* cocotb.scheduler.react) calling it with a reference to the trigger that
* fired. The scheduler can then call next() on all the coroutines that
* are waiting on that particular trigger.
*
* TODO:
* - Tidy up return values
* - Ensure cleanup correctly in exception cases
*
*/
int handle_gpi_callback(void *user_data)
{
int ret = 0;
to_python();
p_callback_data callback_data_p = (p_callback_data)user_data;
if (callback_data_p->id_value != COCOTB_ACTIVE_ID) {
fprintf(stderr, "Userdata corrupted!\n");
ret = 1;
goto err;
}
callback_data_p->id_value = COCOTB_INACTIVE_ID;
/* Cache the sim time */
gpi_get_sim_time(&cache_time.high, &cache_time.low);
PyGILState_STATE gstate;
gstate = TAKE_GIL();
// Python allowed
if (!PyCallable_Check(callback_data_p->function)) {
fprintf(stderr, "Callback fired but function isn't callable?!\n");
ret = 1;
goto out;
}
// Call the callback
PyObject *pValue = PyObject_Call(callback_data_p->function, callback_data_p->args, callback_data_p->kwargs);
// If the return value is NULL a Python exception has occurred
// The best thing to do here is shutdown as any subsequent
// calls will go back to python which is now in an unknown state
if (pValue == NULL)
{
fprintf(stderr, "ERROR: called callback function returned NULL\n");
if (PyErr_Occurred()) {
fprintf(stderr, "Failed to execute callback due to python exception\n");
PyErr_Print();
} else {
fprintf(stderr, "Failed to execute callback\n");
}
gpi_sim_end();
ret = 0;
goto out;
}
// Free up our mess
Py_DECREF(pValue);
// Callbacks may have been re-enabled
if (callback_data_p->id_value == COCOTB_INACTIVE_ID) {
Py_DECREF(callback_data_p->function);
Py_DECREF(callback_data_p->args);
// Free the callback data
free(callback_data_p);
}
out:
DROP_GIL(gstate);
err:
to_simulator();
return ret;
}
开发者ID:TC01,项目名称:cocotb,代码行数:92,代码来源:simulatormodule.c
示例5: create_dynamic_metaobject
//.........这里部分代码省略.........
if (pp->pyqtprop_parsed_type->metatype() == QMetaType::QObjectStar)
{
// However, if the type is a Python sub-class of QObject then we
// use the name of the Python type. This anticipates that the type
// is one that will be proxied by QML at some point.
if (pp->pyqtprop_parsed_type->typeDef() == sipType_QObject)
{
prop_type = ((PyTypeObject *)pp->pyqtprop_parsed_type->py_type())->tp_name;
prop_type.append('*');
}
else
{
prop_type = "QObject*";
}
}
else
{
prop_type = pp->pyqtprop_parsed_type->name();
}
QMetaPropertyBuilder prop_builder = builder.addProperty(prop_name,
prop_type, notifier_id);
// Reset the defaults.
prop_builder.setReadable(false);
prop_builder.setWritable(false);
// Enum or flag.
if (pp->pyqtprop_parsed_type->isEnum() || pp->pyqtprop_parsed_type->isFlag())
{
prop_builder.setEnumOrFlag(true);
}
if (pp->pyqtprop_get && PyCallable_Check(pp->pyqtprop_get))
{
// Readable.
prop_builder.setReadable(true);
}
if (pp->pyqtprop_set && PyCallable_Check(pp->pyqtprop_set))
{
// Writable.
prop_builder.setWritable(true);
// See if the name of the setter follows the Designer convention.
// If so tell the UI compilers not to use setProperty().
PyObject *setter_name_obj = PyObject_GetAttr(pp->pyqtprop_set,
qpycore_dunder_name);
if (setter_name_obj)
{
PyObject *ascii_obj = setter_name_obj;
const char *ascii = sipString_AsASCIIString(&ascii_obj);
Py_DECREF(setter_name_obj);
if (ascii)
{
if (qstrlen(ascii) > 3 && ascii[0] == 's' &&
ascii[1] == 'e' && ascii[2] == 't' &&
ascii[3] == toupper(prop_name[0]) &&
qstrcmp(&ascii[4], &prop_name[1]) == 0)
prop_builder.setStdCppSet(true);
}
Py_DECREF(ascii_obj);
}
开发者ID:ContaTP,项目名称:pyqt5,代码行数:67,代码来源:qpycore_types.cpp
示例6: UDP_func_send
static PyObject *
UDP_func_send(UDP *self, PyObject *args)
{
int r, dest_port, address_type;
char *dest_ip;
uv_buf_t buf;
Py_buffer pbuf;
PyObject *callback;
uv_udp_send_t *wr = NULL;
udp_send_data_t *req_data = NULL;
callback = Py_None;
RAISE_IF_HANDLE_CLOSED(self, PyExc_HandleClosedError, NULL);
if (!PyArg_ParseTuple(args, "(si)s*|O:send", &dest_ip, &dest_port, &pbuf, &callback)) {
return NULL;
}
if (callback != Py_None && !PyCallable_Check(callback)) {
PyBuffer_Release(&pbuf);
PyErr_SetString(PyExc_TypeError, "a callable or None is required");
return NULL;
}
if (dest_port < 0 || dest_port > 65535) {
PyErr_SetString(PyExc_ValueError, "port must be between 0 and 65535");
return NULL;
}
if (pyuv_guess_ip_family(dest_ip, &address_type)) {
PyErr_SetString(PyExc_ValueError, "invalid IP address");
return NULL;
}
Py_INCREF(callback);
wr = (uv_udp_send_t *)PyMem_Malloc(sizeof(uv_udp_send_t));
if (!wr) {
PyErr_NoMemory();
goto error;
}
req_data = (udp_send_data_t*) PyMem_Malloc(sizeof(udp_send_data_t));
if (!req_data) {
PyErr_NoMemory();
goto error;
}
buf = uv_buf_init(pbuf.buf, pbuf.len);
req_data->callback = callback;
req_data->buf_count = 1;
req_data->data.view = pbuf;
wr->data = (void *)req_data;
if (address_type == AF_INET) {
r = uv_udp_send(wr, (uv_udp_t *)UV_HANDLE(self), &buf, 1, uv_ip4_addr(dest_ip, dest_port), (uv_udp_send_cb)on_udp_send);
} else {
r = uv_udp_send6(wr, (uv_udp_t *)UV_HANDLE(self), &buf, 1, uv_ip6_addr(dest_ip, dest_port), (uv_udp_send_cb)on_udp_send);
}
if (r != 0) {
RAISE_UV_EXCEPTION(UV_HANDLE_LOOP(self), PyExc_UDPError);
goto error;
}
Py_RETURN_NONE;
error:
PyBuffer_Release(&pbuf);
Py_DECREF(callback);
if (req_data) {
PyMem_Free(req_data);
}
if (wr) {
PyMem_Free(wr);
}
return NULL;
}
开发者ID:jppommet,项目名称:pyuv,代码行数:79,代码来源:udp.c
示例7: PyErr_SetString
PyObject *pyrna_callback_classmethod_add(PyObject *UNUSED(self), PyObject *args)
{
void *handle;
PyObject *cls;
PyObject *cb_func, *cb_args;
const char *cb_regiontype_str;
const char *cb_event_str;
int cb_event;
int cb_regiontype;
StructRNA *srna;
if (PyTuple_GET_SIZE(args) < 2) {
PyErr_SetString(PyExc_ValueError, "handler_add(handle): expected at least 2 args");
return NULL;
}
cls = PyTuple_GET_ITEM(args, 0);
if (!(srna = pyrna_struct_as_srna(cls, false, "handler_add"))) {
return NULL;
}
cb_func = PyTuple_GET_ITEM(args, 1);
if (!PyCallable_Check(cb_func)) {
PyErr_SetString(PyExc_TypeError, "first argument isn't callable");
return NULL;
}
/* class specific callbacks */
if (RNA_struct_is_a(srna, &RNA_Space)) {
if (!PyArg_ParseTuple(args, "OOO!ss:Space.draw_handler_add",
&cls, &cb_func, /* already assigned, no matter */
&PyTuple_Type, &cb_args, &cb_regiontype_str, &cb_event_str))
{
return NULL;
}
if (pyrna_enum_value_from_id(region_draw_mode_items, cb_event_str, &cb_event, "bpy_struct.callback_add()") == -1) {
return NULL;
}
else if (pyrna_enum_value_from_id(region_type_items, cb_regiontype_str, &cb_regiontype, "bpy_struct.callback_add()") == -1) {
return NULL;
}
else {
const eSpace_Type spaceid = rna_Space_refine_reverse(srna);
if (spaceid == SPACE_EMPTY) {
PyErr_Format(PyExc_TypeError, "unknown space type '%.200s'", RNA_struct_identifier(srna));
return NULL;
}
else {
SpaceType *st = BKE_spacetype_from_id(spaceid);
ARegionType *art = BKE_regiontype_from_id(st, cb_regiontype);
handle = ED_region_draw_cb_activate(art, cb_region_draw, (void *)args, cb_event);
Py_INCREF(args);
}
}
}
else {
PyErr_SetString(PyExc_TypeError, "callback_add(): type does not support callbacks");
return NULL;
}
return PyCapsule_New((void *)handle, RNA_CAPSULE_ID, NULL);
}
开发者ID:flair2005,项目名称:mechanical-blender,代码行数:63,代码来源:bpy_rna_callback.c
示例8: load
virtual void load(const gcore::Path &path, lwc::Registry *reg) {
std::string modulename = path.basename();
modulename = modulename.substr(0, modulename.length()-3);
gcore::Path dirname = path;
dirname.pop();
dirname.makeAbsolute().normalize();
addToSysPath(dirname);
PyObject *pymodname;
pymodname = PyString_FromString(modulename.c_str());
PyObject *mod = PyImport_Import(pymodname);
Py_DECREF(pymodname);
if (!mod) {
std::cout << "pyloader: Could not load python module" << std::endl;
PyErr_Print();
return;
}
PyObject *getCountFunc = PyObject_GetAttrString(mod, "LWC_ModuleGetTypeCount");
if (!getCountFunc || !PyCallable_Check(getCountFunc)) {
if (getCountFunc) {
Py_DECREF(getCountFunc);
}
Py_DECREF(mod);
return;
}
PyObject *getNameFunc = PyObject_GetAttrString(mod, "LWC_ModuleGetTypeName");
if (!getNameFunc || !PyCallable_Check(getNameFunc)) {
Py_DECREF(getCountFunc);
if (getNameFunc) {
Py_DECREF(getNameFunc);
}
Py_DECREF(mod);
return;
}
PyObject *getClassFunc = PyObject_GetAttrString(mod, "LWC_ModuleGetTypeClass");
if (!getClassFunc || !PyCallable_Check(getClassFunc)) {
Py_DECREF(getCountFunc);
Py_DECREF(getNameFunc);
if (getClassFunc) {
Py_DECREF(getClassFunc);
}
Py_DECREF(mod);
return;
}
PyObject *count = PyObject_CallObject(getCountFunc, NULL);
long n = PyInt_AsLong(count);
Py_DECREF(count);
PyObject *args = PyTuple_New(1);
for (long i=0; i<n; ++i) {
// will this DECREF the old index?
PyTuple_SetItem(args, 0, PyInt_FromLong(i));
PyObject *pname = PyObject_CallObject(getNameFunc, args);
PyObject *klass = PyObject_CallObject(getClassFunc, args);
if (!klass) {
std::cout << "pyloader: No class object for type" << std::endl;
continue;
}
char *tn = PyString_AsString(pname);
if (!reg->hasType(tn)) {
if (mFactory->addType(tn, klass)) {
registerType(tn, mFactory, reg);
} else {
std::cout << "pyloader: Invalid type \"" << tn << "\"" << std::endl;
}
} else {
std::cout << "pyloader: Type \"" << tn << "\" already registered" << std::endl;
}
Py_DECREF(pname);
Py_DECREF(klass);
}
Py_DECREF(args);
Py_DECREF(getCountFunc);
Py_DECREF(getNameFunc);
Py_DECREF(getClassFunc);
mPyModules.push_back(mod);
}
开发者ID:gatgui,项目名称:lwc,代码行数:93,代码来源:pyloader.cpp
示例9: child_init
static int child_init(int rank)
{
PyObject *pFunc, *pArgs, *pValue, *pResult;
int rval;
char *classname;
PyEval_AcquireLock();
PyThreadState_Swap(myThreadState);
// get instance class name
classname = get_instance_class_name(handler_obj);
if (classname == NULL)
{
if (!PyErr_Occurred())
PyErr_Format(PyExc_AttributeError, "'module' instance has no class name");
python_handle_exception("child_init");
Py_DECREF(format_exc_obj);
Py_XDECREF(classname);
PyThreadState_Swap(NULL);
PyEval_ReleaseLock();
return -1;
}
pFunc = PyObject_GetAttrString(handler_obj, child_init_mname.s);
if (pFunc == NULL) {
python_handle_exception("child_init");
Py_XDECREF(pFunc);
Py_DECREF(format_exc_obj);
PyThreadState_Swap(NULL);
PyEval_ReleaseLock();
return -1;
}
if (!PyCallable_Check(pFunc)) {
if (!PyErr_Occurred())
PyErr_Format(PyExc_AttributeError, "class object '%s' has is not callable attribute '%s'", !classname ? "None" : classname, mod_init_fname.s);
python_handle_exception("child_init");
Py_DECREF(format_exc_obj);
Py_XDECREF(classname);
Py_XDECREF(pFunc);
PyThreadState_Swap(NULL);
PyEval_ReleaseLock();
return -1;
}
pArgs = PyTuple_New(1);
if (pArgs == NULL) {
python_handle_exception("child_init");
Py_DECREF(format_exc_obj);
Py_XDECREF(classname);
Py_DECREF(pFunc);
PyThreadState_Swap(NULL);
PyEval_ReleaseLock();
return -1;
}
pValue = PyInt_FromLong((long)rank);
if (pValue == NULL) {
python_handle_exception("child_init");
Py_DECREF(format_exc_obj);
Py_DECREF(pArgs);
Py_DECREF(pFunc);
PyThreadState_Swap(NULL);
PyEval_ReleaseLock();
return -1;
}
PyTuple_SetItem(pArgs, 0, pValue);
/* pValue has been stolen */
pResult = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pFunc);
Py_DECREF(pArgs);
if (PyErr_Occurred()) {
python_handle_exception("child_init");
Py_DECREF(format_exc_obj);
Py_XDECREF(pResult);
PyThreadState_Swap(NULL);
PyEval_ReleaseLock();
return -1;
}
if (pResult == NULL) {
LM_ERR("PyObject_CallObject() returned NULL but no exception!\n");
PyThreadState_Swap(NULL);
PyEval_ReleaseLock();
return -1;
}
if (!PyInt_Check(pResult))
{
if (!PyErr_Occurred())
PyErr_Format(PyExc_TypeError, "method '%s' of class '%s' should return 'int' type", child_init_mname.s, !classname ? "None" : classname);
python_handle_exception("child_init");
Py_DECREF(format_exc_obj);
Py_XDECREF(pResult);
//.........这里部分代码省略.........
开发者ID:billyyh,项目名称:kamailio,代码行数:101,代码来源:python_mod.c
示例10: mod_init
static int mod_init(void)
{
char *dname_src, *bname_src;
int i;
PyObject *sys_path, *pDir, *pModule, *pFunc, *pArgs;
PyThreadState *mainThreadState;
if (script_name.len == 0) {
script_name.len = strlen(script_name.s);
}
if (mod_init_fname.len == 0) {
mod_init_fname.len = strlen(mod_init_fname.s);
}
if (child_init_mname.len == 0) {
child_init_mname.len = strlen(child_init_mname.s);
}
dname_src = as_asciiz(&script_name);
bname_src = as_asciiz(&script_name);
if(dname_src==NULL || bname_src==NULL)
{
LM_ERR("no more pkg memory\n");
return -1;
}
dname = strdup(dirname(dname_src));
if (strlen(dname) == 0)
dname = ".";
bname = strdup(basename(bname_src));
i = strlen(bname);
if (bname[i - 1] == 'c' || bname[i - 1] == 'o')
i -= 1;
if (bname[i - 3] == '.' && bname[i - 2] == 'p' && bname[i - 1] == 'y') {
bname[i - 3] = '\0';
} else {
LM_ERR("%s: script_name doesn't look like a python script\n",
script_name.s);
return -1;
}
Py_Initialize();
PyEval_InitThreads();
mainThreadState = PyThreadState_Get();
format_exc_obj = InitTracebackModule();
if (format_exc_obj == NULL || !PyCallable_Check(format_exc_obj))
{
Py_XDECREF(format_exc_obj);
PyEval_ReleaseLock();
return -1;
}
sys_path = PySys_GetObject("path");
/* PySys_GetObject doesn't pass reference! No need to DEREF */
if (sys_path == NULL) {
if (!PyErr_Occurred())
PyErr_Format(PyExc_AttributeError, "'module' object 'sys' has no attribute 'path'");
python_handle_exception("mod_init");
Py_DECREF(format_exc_obj);
PyEval_ReleaseLock();
return -1;
}
pDir = PyString_FromString(dname);
if (pDir == NULL) {
if (!PyErr_Occurred())
PyErr_Format(PyExc_AttributeError, "PyString_FromString() has failed");
python_handle_exception("mod_init");
Py_DECREF(format_exc_obj);
PyEval_ReleaseLock();
return -1;
}
PyList_Insert(sys_path, 0, pDir);
Py_DECREF(pDir);
if (init_modules() != 0) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_AttributeError, "init_modules() has failed");
python_handle_exception("mod_init");
Py_DECREF(format_exc_obj);
PyEval_ReleaseLock();
return -1;
}
if (python_msgobj_init() != 0) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_AttributeError, "python_msgobj_init() has failed");
python_handle_exception("mod_init");
Py_DECREF(format_exc_obj);
PyEval_ReleaseLock();
return -1;
}
pModule = PyImport_ImportModule(bname);
if (pModule == NULL) {
if (!PyErr_Occurred())
//.........这里部分代码省略.........
开发者ID:billyyh,项目名称:kamailio,代码行数:101,代码来源:python_mod.c
示例11: _pygi_marshal_from_py_interface_callback
static gboolean
_pygi_marshal_from_py_interface_callback (PyGIInvokeState *state,
PyGICallableCache *callable_cache,
PyGIArgCache *arg_cache,
PyObject *py_arg,
GIArgument *arg,
gpointer *cleanup_data)
{
GICallableInfo *callable_info;
PyGICClosure *closure;
PyGIArgCache *user_data_cache = NULL;
PyGIArgCache *destroy_cache = NULL;
PyGICallbackCache *callback_cache;
PyObject *py_user_data = NULL;
callback_cache = (PyGICallbackCache *)arg_cache;
if (callback_cache->user_data_index > 0) {
user_data_cache = _pygi_callable_cache_get_arg (callable_cache, callback_cache->user_data_index);
if (user_data_cache->py_arg_index < state->n_py_in_args) {
/* py_user_data is a borrowed reference. */
py_user_data = PyTuple_GetItem (state->py_in_args, user_data_cache->py_arg_index);
if (!py_user_data)
return FALSE;
/* NULL out user_data if it was not supplied and the default arg placeholder
* was used instead.
*/
if (py_user_data == _PyGIDefaultArgPlaceholder) {
py_user_data = NULL;
} else if (callable_cache->user_data_varargs_index < 0) {
/* For non-variable length user data, place the user data in a
* single item tuple which is concatenated to the callbacks arguments.
* This allows callback input arg marshaling to always expect a
* tuple for user data. Note the
*/
py_user_data = Py_BuildValue("(O)", py_user_data, NULL);
} else {
/* increment the ref borrowed from PyTuple_GetItem above */
Py_INCREF (py_user_data);
}
}
}
if (py_arg == Py_None) {
return TRUE;
}
if (!PyCallable_Check (py_arg)) {
PyErr_Format (PyExc_TypeError,
"Callback needs to be a function or method not %s",
py_arg->ob_type->tp_name);
return FALSE;
}
callable_info = (GICallableInfo *)callback_cache->interface_info;
closure = _pygi_make_native_closure (callable_info, callback_cache->scope, py_arg, py_user_data);
arg->v_pointer = closure->closure;
/* always decref the user data as _pygi_make_native_closure adds its own ref */
Py_XDECREF (py_user_data);
/* The PyGICClosure instance is used as user data passed into the C function.
* The return trip to python will marshal this back and pull the python user data out.
*/
if (user_data_cache != NULL) {
state->args[user_data_cache->c_arg_index].arg_value.v_pointer = closure;
}
/* Setup a GDestroyNotify callback if this method supports it along with
* a user data field. The user data field is a requirement in order
* free resources and ref counts associated with this arguments closure.
* In case a user data field is not available, show a warning giving
* explicit information and setup a dummy notification to avoid a crash
* later on in _pygi_destroy_notify_callback_closure.
*/
if (callback_cache->destroy_notify_index > 0) {
destroy_cache = _pygi_callable_cache_get_arg (callable_cache, callback_cache->destroy_notify_index);
}
if (destroy_cache) {
if (user_data_cache != NULL) {
state->args[destroy_cache->c_arg_index].arg_value.v_pointer = _pygi_invoke_closure_free;
} else {
char *full_name = pygi_callable_cache_get_full_name (callable_cache);
gchar *msg = g_strdup_printf("Callables passed to %s will leak references because "
"the method does not support a user_data argument. "
"See: https://bugzilla.gnome.org/show_bug.cgi?id=685598",
full_name);
g_free (full_name);
if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 2)) {
g_free(msg);
_pygi_invoke_closure_free(closure);
return FALSE;
}
g_free(msg);
state->args[destroy_cache->c_arg_index].arg_value.v_pointer = _pygi_destroy_notify_dummy;
}
}
//.........这里部分代码省略.........
开发者ID:Distrotech,项目名称:pygobject,代码行数:101,代码来源:pygi-closure.c
示例12: main
int main(int argc, char *argv[])
{
Py_Initialize();
if(!Py_IsInitialized())
{
return -1;
}
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
PyObject* pName;
PyObject* pModule;
PyObject* pDict;
PyObject* pFunc;
pName = PyString_FromString("call");
pModule = PyImport_Import(pName);
if(!pModule)
{
printf("can't find call.py");
getchar();
return -1;
}
pDict = PyModule_GetDict(pModule);
if(!pDict)
{
return -1;
}
{
pFunc = PyDict_GetItemString(pDict,"test");
if(!pFunc || !PyCallable_Check(pFunc))
{
printf("can't find function [test]");
getchar();
return -1;
}
PyObject_CallObject(pFunc,0);
}
{
pFunc = PyDict_GetItemString(pDict,"add");
if(!pFunc || !PyCallable_Check(pFunc))
{
printf("can't find function [test]");
getchar();
return -1;
}
PyObject* args = PyTuple_New(2);
PyTuple_SetItem(args,0,Py_BuildValue("l",3));
PyTuple_SetItem(args,1,Py_BuildValue("l",4));
PyObject *pAdded = PyObject_CallObject(pFunc,args);
int ret = PyInt_AsLong(pAdded);
printf("add value:%d\n",ret);
Py_DECREF(args);
}
Py_DECREF(pName);
Py_DECREF(pDict);
Py_DECREF(pModule);
Py_Finalize();
system("PAUSE");
return 0;
}
开发者ID:weikent,项目名称:Python,代码行数:67,代码来源:main.c
示例13: Channel_func_query
static PyObject *
Channel_func_query(Channel *self, PyObject *args)
{
char *name;
int query_type;
PyObject *callback, *ret;
CHECK_CHANNEL(self);
if (!PyArg_ParseTuple(args, "etiO:query", "idna", &name, &query_type, &callback)) {
return NULL;
}
if (!PyCallable_Check(callback)) {
PyErr_SetString(PyExc_TypeError, "a callable is required");
ret = NULL;
goto finally;
}
Py_INCREF(callback);
switch (query_type) {
case T_A:
{
ares_query(self->channel, name, C_IN, T_A, &query_a_cb, (void *)callback);
break;
}
case T_AAAA:
{
ares_query(self->channel, name, C_IN, T_AAAA, &query_aaaa_cb, (void *)callback);
break;
}
case T_CNAME:
{
ares_query(self->channel, name, C_IN, T_CNAME, &query_cname_cb, (void *)callback);
break;
}
case T_MX:
{
ares_query(self->channel, name, C_IN, T_MX, &query_mx_cb, (void *)callback);
break;
}
case T_NAPTR:
{
ares_query(self->channel, name, C_IN, T_NAPTR, &query_naptr_cb, (void *)callback);
break;
}
case T_NS:
{
ares_query(self->channel, name, C_IN, T_NS, &query_ns_cb, (void *)callback);
break;
}
case T_PTR:
{
ares_query(self->channel, name, C_IN, T_PTR, &query_ptr_cb, (void *)callback);
break;
}
case T_SOA:
{
ares_query(self->channel, name, C_IN, T_SOA, &query_soa_cb, (void *)callback);
break;
}
case T_SRV:
{
ares_query(self->channel, name, C_IN, T_SRV, &query_srv_cb, (void *)callback);
break;
}
case T_TXT:
{
ares_query(self->channel, name, C_IN, T_TXT, &query_txt_cb, (void *)callback);
break;
}
default:
{
Py_DECREF(callback);
PyErr_SetString(PyExc_ValueError, "invalid query type specified");
ret = NULL;
goto finally;
}
}
ret = Py_None;
finally:
PyMem_Free(name);
Py_XINCREF(ret);
return ret;
}
开发者ID:aguinet,项目名称:pycares,代码行数:97,代码来源:cares.c
示例14: PyErr_Clear
// this code is heavily adapted from the paint license, which is in
// the file paint.license (BSD compatible) included in this
// distribution. TODO, add license file to MANIFEST.in and CVS
Py::Object _png_module::write_png(const Py::Tuple& args)
{
args.verify_length(4, 5);
FILE *fp = NULL;
bool close_file = false;
bool close_dup_file = false;
Py::Object buffer_obj = Py::Object(args[0]);
PyObject* buffer = buffer_obj.ptr();
if (!PyObject_CheckReadBuffer(buffer))
{
throw Py::TypeError("First argument must be an rgba buffer.");
}
const void* pixBufferPtr = NULL;
Py_ssize_t pixBufferLength = 0;
if (PyObject_AsReadBuffer(buffer, &pixBufferPtr, &pixBufferLength))
{
throw Py::ValueError("Couldn't get data from read buffer.");
}
png_byte* pixBuffer = (png_byte*)pixBufferPtr;
int width = (int)Py::Int(args[1]);
int height = (int)Py::Int(args[2]);
if (pixBufferLength < width * height * 4)
{
throw Py::ValueError("Buffer and width, height don't seem to match.");
}
Py::Object py_fileobj = Py::Object(args[3]);
PyObject* py_file = NULL;
if (py_fileobj.isString())
{
if ((py_file = npy_PyFile_OpenFile(py_fileobj.ptr(), (char *)"wb")) == NULL) {
throw Py::Exception();
}
close_file = true;
}
else
{
py_file = py_fileobj.ptr();
}
if ((fp = npy_PyFile_Dup(py_file, (char *)"wb")))
{
close_dup_file = true;
}
else
{
PyErr_Clear();
PyObject* write_method = PyObject_GetAttrString(
py_file, "write");
if (!(write_method && PyCallable_Check(write_method)))
{
Py_XDECREF(write_method);
throw Py::TypeError(
"Object does not appear to be a 8-bit string path or "
"a Python file-like object");
}
Py_XDECREF(write_method);
}
png_bytep *row_pointers = NULL;
png_structp png_ptr = NULL;
png_infop info_ptr = NULL;
try
{
struct png_color_8_struct sig_bit;
png_uint_32 row;
row_pointers = new png_bytep[height];
for (row = 0; row < (png_uint_32)height; ++row)
{
row_pointers[row] = pixBuffer + row * width * 4;
}
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL)
{
throw Py::RuntimeError("Could not create write struct");
}
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
{
throw Py::RuntimeError("Could not create info struct");
}
if (setjmp(png_jmpbuf(png_ptr)))
{
throw Py::RuntimeError("Error building image");
}
if (fp)
{
//.........这里部分代码省略.........
开发者ID:Nuevalgo,项目名称:Feedbot,代码行数:101,代码来源:_png.cpp
示例15: PyGILState_Ensure
void PythonTransform::transform(const QByteArray &input, QByteArray &output)
{
if (input.isEmpty())
return;
PyGILState_STATE lgstate;
lgstate = PyGILState_Ensure();
if (loadModule()) {
PyObject * pyInbound = Py_False; // need reference count management
if (twoWays)
pyInbound = (wayValue == INBOUND ? Py_True : Py_False );
Py_INCREF(pyInbound);
if (PyModule_AddObject(pModule, INBOUND_ATTR_NAME, pyInbound) == -1) { // steal reference
pythonmgm->checkPyError();
logError(tr("T_T Could not set the direction value properly:\n%1").arg(pythonmgm->getLastError()),id);
Py_XDECREF(pyInbound);
}
// setting parameters in the python environment
if (!parameters.isEmpty()) {
PyObject *paramsdict = PyDict_New();
if (!pythonmgm->checkPyError()) {
logError(tr("T_T Error while creating the Python parameter dict:\n%1").arg(pythonmgm->getLastError()), id);
Py_XDECREF(paramsdict);
PyGILState_Release(lgstate);
return;
}
// adding parameters to the python list
QHashIterator<QByteArray, QByteArray> i(parameters);
while (i.hasNext()) {
i.next();
PyObject* paramKey = PyUnicode_FromStringAndSize(i.key(),i.key().size());
if (!pythonmgm->checkPyError()) {
logError(tr("T_T Error while creating Python parameter key:\n%1").arg(pythonmgm->getLastError()), id);
Py_XDECREF(paramsdict);
PyGILState_Release(lgstate);
return;
}
PyObject* paramValue = PyUnicode_FromStringAndSize(i.value(),i.value().size());
if (!pythonmgm->checkPyError()) {
logError(tr("T_T Error while creating Python parameter value:\n%1").arg(pythonmgm->getLastError()), id);
Py_XDECREF(paramsdict);
Py_XDECREF(paramKey);
PyGILState_Release(lgstate);
return;
}
if (PyDict_SetItem(paramsdict,paramKey,paramValue) == -1) { // stealing reference
pythonmgm->checkPyError(); // we already know there was an error
logError(tr("T_T Error while setting Python parameter pair:\n%1").arg(pythonmgm->getLastError()), id);
Py_XDECREF(paramsdict);
Py_XDECREF(paramKey);
Py_XDECREF(paramValue);
PyGILState_Release(lgstate);
return;
}
// Cleaning the values (references not stolen)
Py_XDECREF(paramKey);
Py_XDECREF(paramValue);
}
if (PyModule_AddObject(pModule,PARAMS_ATTR_NAME , paramsdict) == -1) { // stolen paramsdict reference
pythonmgm->checkPyError();
logError(tr("T_T Could not set the Pip3line_params value properly:\n%1").arg(pythonmgm->getLastError()),id);
}
} else {
Py_INCREF(Py_None);
if (PyModule_AddObject(pModule,PARAMS_ATTR_NAME , Py_None) == -1) { // stealing reference
pythonmgm->checkPyError();
logError(tr("T_T Could not set the Pip3line_params None value properly:\n%1").arg(pythonmgm->getLastError()),id);
Py_DECREF(Py_None);
}
}
PyObject * pFunc = PyObject_GetAttrString(pModule, MAIN_FUNCTION_NAME);
if (pythonmgm->checkPyError() && PyCallable_Check(pFunc)) {
PyObject* pArgs = PyTuple_New(1);
if (!pythonmgm->checkPyError()) {
Q_EMIT error(tr("T_T Error while creating the Python argument tuple:\n%1").arg(pythonmgm->getLastError()), id);
Py_XDECREF(pFunc);
Py_XDECREF(pArgs);
PyGILState_Release(lgstate);
return;
}
PyObject* inputPy = PyByteArray_FromStringAndSize(input.data(),input.size());
if (!pythonmgm->checkPyError()) {
Q_EMIT error(tr("T_T Error while creating the Python byte array:\n%1").arg(pythonmgm->getLastError()), id);
Py_XDECREF(pFunc);
Py_XDECREF(pArgs);
Py_XDECREF(inputPy);
PyGILState_Release(lgstate);
//.........这里部分代码省略.........
开发者ID:nccgroup,项目名称:pip3line,代码行数:101,代码来源:pythontransform.cpp
|
请发表评论