First upload, 18 controller version

This commit is contained in:
2026-04-14 15:23:56 +02:00
commit 8c55001a1c
3810 changed files with 764061 additions and 0 deletions

Binary file not shown.

View File

@@ -0,0 +1,37 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
from __future__ import annotations
"""
This file contains the exact signatures for all functions in module
Shiboken, except for defaults which are replaced by "...".
"""
# Module `Shiboken`
from shiboken6 import Shiboken
class Object:
def __init__(self) -> None: ...
class VoidPtr:
def __init__(self, value: int) -> None: ...
def _unpickle_enum(arg__1: object, arg__2: object) -> object: ...
def createdByPython(arg__1: Shiboken.Object) -> bool: ...
def delete(arg__1: Shiboken.Object) -> None: ...
def dump(arg__1: object) -> str: ...
def getAllValidWrappers() -> list[Shiboken.Object]: ...
def getCppPointer(arg__1: Shiboken.Object) -> tuple[int, ...]: ...
def invalidate(arg__1: Shiboken.Object) -> None: ...
def isValid(arg__1: object) -> bool: ...
def ownedByPython(arg__1: Shiboken.Object) -> bool: ...
def wrapInstance(arg__1: int, arg__2: type) -> Shiboken.Object: ...
# eof

View File

@@ -0,0 +1,27 @@
__version__ = "6.10.2"
__version_info__ = (6, 10, 2, "", "")
__minimum_python_version__ = (3, 9)
__maximum_python_version__ = (3, 14)
# PYSIDE-932: Python 2 cannot import 'zipfile' for embedding while being imported, itself.
# We simply pre-load all imports for the signature extension.
# Also, PyInstaller seems not always to be reliable in finding modules.
# We explicitly import everything that is needed:
import sys
import os
import zipfile
import base64
import marshal
import io
import contextlib
import textwrap
import traceback
import types
import struct
import re
import tempfile
import keyword
import functools
import typing
from shiboken6.Shiboken import *

View File

@@ -0,0 +1,12 @@
shiboken_library_soversion = "6.10"
version = "6.10.2"
version_info = (6, 10, 2, "", "")
__build_date__ = '2026-01-29T22:16:19+00:00'
__setup_py_package_version__ = '6.10.2'

View File

@@ -0,0 +1,20 @@
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
from __future__ import annotations
major_version = "6"
minor_version = "10"
patch_version = "2"
# For example: "a", "b", "rc"
# (which means "alpha", "beta", "release candidate").
# An empty string means the generated package will be an official release.
release_version_type = ""
# For example: "1", "2" (which means "beta1", "beta2", if type is "b").
pre_release_version = ""
if __name__ == '__main__':
# Used by CMake.
print(f'{major_version};{minor_version};{patch_version};'
f'{release_version_type};{pre_release_version}')

Binary file not shown.

View File

@@ -0,0 +1,83 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef AUTODECREF_H
#define AUTODECREF_H
#include "sbkpython.h"
#include <utility>
struct SbkObject;
namespace Shiboken
{
/**
* AutoDecRef holds a PyObject pointer and decrement its reference counter when destroyed.
*/
struct AutoDecRef
{
public:
AutoDecRef(const AutoDecRef &) = delete;
AutoDecRef(AutoDecRef &&o) noexcept : m_pyObj{std::exchange(o.m_pyObj, nullptr)} {}
AutoDecRef &operator=(const AutoDecRef &) = delete;
AutoDecRef &operator=(AutoDecRef &&o) noexcept
{
m_pyObj = std::exchange(o.m_pyObj, nullptr);
return *this;
}
/// AutoDecRef constructor.
/// \param pyobj A borrowed reference to a Python object
explicit AutoDecRef(PyObject *pyObj) noexcept : m_pyObj(pyObj) {}
/// AutoDecRef constructor.
/// \param pyobj A borrowed reference to a wrapped Python object
explicit AutoDecRef(SbkObject *pyObj) noexcept : m_pyObj(reinterpret_cast<PyObject *>(pyObj)) {}
/// AutoDecref default constructor.
/// To be used later with reset():
AutoDecRef() noexcept = default;
/// Decref the borrowed python reference
~AutoDecRef()
{
Py_XDECREF(m_pyObj);
}
[[nodiscard]] bool isNull() const { return m_pyObj == nullptr; }
/// Returns the pointer of the Python object being held.
[[nodiscard]] PyObject *object() const { return m_pyObj; }
[[nodiscard]] operator PyObject *() const { return m_pyObj; }
operator bool() const { return m_pyObj != nullptr; }
PyObject *operator->() { return m_pyObj; }
template<typename T>
[[deprecated]] T cast()
{
return reinterpret_cast<T>(m_pyObj);
}
/**
* Decref the current borrowed python reference and borrow \p other.
*/
void reset(PyObject *other)
{
// Safely decref m_pyObj. See Py_XSETREF in object.h .
PyObject *_py_tmp = m_pyObj;
m_pyObj = other;
Py_XDECREF(_py_tmp);
}
PyObject *release()
{
PyObject *result = m_pyObj;
m_pyObj = nullptr;
return result;
}
private:
PyObject *m_pyObj = nullptr;
};
} // namespace Shiboken
#endif // AUTODECREF_H

View File

@@ -0,0 +1,531 @@
// Copyright (C) 2019 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef BASEWRAPPER_H
#define BASEWRAPPER_H
#include "sbkpython.h"
#include "shibokenmacros.h"
#include "sbkmodule.h"
#include "gilstate.h"
#include <vector>
#include <string>
extern "C"
{
struct SbkConverter;
struct SbkObjectPrivate;
/// Base Python object for all the wrapped C++ classes.
struct LIBSHIBOKEN_API SbkObject
{
PyObject_HEAD
/// Instance dictionary.
PyObject *ob_dict;
/// List of weak references
PyObject *weakreflist;
SbkObjectPrivate *d;
};
/// PYSIDE-939: A general replacement for object_dealloc.
LIBSHIBOKEN_API void Sbk_object_dealloc(PyObject *self);
/// Dealloc the python object \p pyObj and the C++ object represented by it.
LIBSHIBOKEN_API void SbkDeallocWrapper(PyObject *pyObj);
LIBSHIBOKEN_API void SbkDeallocQAppWrapper(PyObject *pyObj);
LIBSHIBOKEN_API void SbkDeallocWrapperWithPrivateDtor(PyObject *self);
/// Function signature for the multiple inheritance information initializers that should be provided by classes with multiple inheritance.
using MultipleInheritanceInitFunction = int *(*)(const void *);
/**
* Special cast function is used to correctly cast an object when it's
* part of a multiple inheritance hierarchy.
* The implementation of this function is auto generated by the generator and you don't need to care about it.
*/
using SpecialCastFunction = void *(*)(void *, PyTypeObject *);
using TypeDiscoveryFunc = PyTypeObject *(*)(void *, PyTypeObject *);
using TypeDiscoveryFuncV2 = void *(*)(void *, PyTypeObject *);
// Used in userdata dealloc function
using DeleteUserDataFunc = void (*)(void *);
using ObjectDestructor = void (*)(void *);
using SubTypeInitHook = void (*)(PyTypeObject *, PyObject *, PyObject *);
/// PYSIDE-1019: Set the function to select the current feature.
/// Return value is the previous content.
using SelectableFeatureHook = void (*)(PyTypeObject *);
using SelectableFeatureCallback = void (*)(bool);
LIBSHIBOKEN_API SelectableFeatureHook initSelectableFeature(SelectableFeatureHook func);
LIBSHIBOKEN_API void setSelectableFeatureCallback(SelectableFeatureCallback func);
/// PYSIDE-1626: Enforcing a context switch without further action.
LIBSHIBOKEN_API void SbkObjectType_UpdateFeature(PyTypeObject *type);
/// PYSIDE-1019: Get access to PySide property strings.
LIBSHIBOKEN_API const char **SbkObjectType_GetPropertyStrings(PyTypeObject *type);
LIBSHIBOKEN_API void SbkObjectType_SetPropertyStrings(PyTypeObject *type, const char **strings);
/// PYSIDE-1735: Store the enumFlagInfo.
LIBSHIBOKEN_API void SbkObjectType_SetEnumFlagInfo(PyTypeObject *type, const char **strings);
/// PYSIDE-1470: Set the function to kill a Q*Application.
using DestroyQAppHook = void(*)();
LIBSHIBOKEN_API void setDestroyQApplication(DestroyQAppHook func);
/// PYSIDE-535: Use the C API in PyPy instead of `op->ob_dict`, directly (borrowed ref)
LIBSHIBOKEN_API PyObject *SbkObject_GetDict_NoRef(PyObject *op);
extern LIBSHIBOKEN_API PyTypeObject *SbkObjectType_TypeF(void);
extern LIBSHIBOKEN_API PyTypeObject *SbkObject_TypeF(void);
struct SbkObjectTypePrivate;
/// PyTypeObject extended with C++ multiple inheritance information.
LIBSHIBOKEN_API PyObject *SbkObject_tp_new(PyTypeObject *subtype, PyObject *, PyObject *);
/// The special case of a switchable singleton Q*Application.
LIBSHIBOKEN_API PyObject *SbkQApp_tp_new(PyTypeObject *subtype, PyObject *, PyObject *);
/// Create a new Q*Application wrapper and monitor it.
LIBSHIBOKEN_API PyObject *MakeQAppWrapper(PyTypeObject *type);
/**
* PYSIDE-832: Use object_dealloc instead of nullptr.
*
* When moving to heaptypes, we were struck by a special default behavior of
* PyType_FromSpec that inserts subtype_dealloc when tp_dealloc is
* nullptr. But the default before conversion to heaptypes was to assign
* object_dealloc. This seems to be a bug in the Limited API.
*/
/// PYSIDE-939: Replaced by Sbk_object_dealloc.
LIBSHIBOKEN_API PyObject *SbkDummyNew(PyTypeObject *type, PyObject *, PyObject *);
/// PYSIDE-74: Fallback used in all types now.
LIBSHIBOKEN_API PyObject *FallbackRichCompare(PyObject *self, PyObject *other, int op);
/// PYSIDE-1970: Be easily able to see what is happening in the running code.
LIBSHIBOKEN_API void disassembleFrame(const char *marker);
/// PYSIDE-2230: Check if an object is an SbkObject.
LIBSHIBOKEN_API bool SbkObjectType_Check(PyTypeObject *type);
/// PYSIDE-2701: Some improvements from folding optimizations.
LIBSHIBOKEN_API PyObject *Sbk_ReturnFromPython_None();
LIBSHIBOKEN_API PyObject *Sbk_ReturnFromPython_Result(PyObject *pyResult);
LIBSHIBOKEN_API PyObject *Sbk_ReturnFromPython_Self(PyObject *self);
} // extern "C"
LIBSHIBOKEN_API PyObject *Sbk_GetPyOverride(const void *voidThis, PyTypeObject *typeObject,
Shiboken::GilState &gil, const char *funcName,
PyObject *&resultCache, PyObject **nameCache);
namespace Shiboken
{
/**
* Init shiboken library.
*/
LIBSHIBOKEN_API void init();
/// PYSIDE-1415: Publish Shiboken objects.
LIBSHIBOKEN_API void initShibokenSupport(PyObject *module);
/// Delete the class T allocated on \p cptr.
template<typename T>
void callCppDestructor(void *cptr)
{
delete reinterpret_cast<T *>(cptr);
}
/// setErrorAboutWrongArguments now gets overload information from the signature module.
/// The extra info argument can contain additional data about the error.
LIBSHIBOKEN_API void setErrorAboutWrongArguments(PyObject *args, const char *funcName,
PyObject *info, const char *className = nullptr);
/// Return values for the different return variants.
/// This is used instead of goto.
/// Either funcname should contain the full function name, or the module and class
/// are taken from the TypeInitStruct.
LIBSHIBOKEN_API PyObject *returnWrongArguments(PyObject *args, const char *funcName, PyObject *info,
Module::TypeInitStruct initStruct = {nullptr, nullptr});
LIBSHIBOKEN_API int returnWrongArguments_Zero(PyObject *args, const char *funcName, PyObject *info,
Module::TypeInitStruct initStruct = {nullptr, nullptr});
LIBSHIBOKEN_API int returnWrongArguments_MinusOne(PyObject *args, const char *funcName, PyObject *info,
Module::TypeInitStruct initStruct = {nullptr, nullptr});
/// A simple special version for the end of rich comparison.
LIBSHIBOKEN_API PyObject *returnFromRichCompare(PyObject *result);
// Return error information object if the argument count is wrong
LIBSHIBOKEN_API PyObject *checkInvalidArgumentCount(Py_ssize_t numArgs,
Py_ssize_t minArgs,
Py_ssize_t maxArgs);
namespace ObjectType {
/**
* Returns true if the object is an instance of a type created by the Shiboken generator.
*/
LIBSHIBOKEN_API bool checkType(PyTypeObject *pyObj);
/**
* Returns true if this object is an instance of an user defined type derived from an Shiboken type.
*/
LIBSHIBOKEN_API bool isUserType(PyTypeObject *pyObj);
/**
* Returns true if the constructor of \p ctorType can be called for a instance of type \p myType.
* \note This function set a python error when returning false.
*/
LIBSHIBOKEN_API bool canCallConstructor(PyTypeObject *myType, PyTypeObject *ctorType);
/**
* Tells if the \p type represents an object of a class with multiple inheritance in C++.
* When this occurs, the C++ pointer held by the Python wrapper will need to be cast when
* passed as a parameter that expects a type of its ancestry.
* \returns true if a call to ObjectType::cast() is needed to obtain the correct
* C++ pointer for Python objects of type \p type.
*/
LIBSHIBOKEN_API bool hasCast(PyTypeObject *type);
/**
* Cast the C++ pointer held by a Python object \p obj of type \p sourceType,
* to a C++ pointer of a C++ class indicated by type \p targetType.
* \returns The cast C++ pointer.
*/
LIBSHIBOKEN_API void *cast(PyTypeObject *sourceType, SbkObject *obj, PyTypeObject *targetType);
/// Set the C++ cast function for \p type.
LIBSHIBOKEN_API void setCastFunction(PyTypeObject *type, SpecialCastFunction func);
LIBSHIBOKEN_API void setOriginalName(PyTypeObject *self, const char *name);
LIBSHIBOKEN_API const char *getOriginalName(PyTypeObject *self);
LIBSHIBOKEN_API void setTypeDiscoveryFunctionV2(PyTypeObject *self, TypeDiscoveryFuncV2 func);
LIBSHIBOKEN_API void copyMultipleInheritance(PyTypeObject *self, PyTypeObject *other);
LIBSHIBOKEN_API void setMultipleInheritanceFunction(PyTypeObject *self, MultipleInheritanceInitFunction func);
LIBSHIBOKEN_API MultipleInheritanceInitFunction getMultipleInheritanceFunction(PyTypeObject *type);
LIBSHIBOKEN_API void setDestructorFunction(PyTypeObject *self, ObjectDestructor func);
enum WrapperFlags
{
InnerClass = 0x1,
DeleteInMainThread = 0x2,
Value = 0x4,
InternalWrapper = 0x8
};
/**
* Initializes a Shiboken wrapper type and adds it to the module,
* or to the enclosing class if the type is an inner class.
* This function also calls setDestructorFunction.
* \param enclosingObject The module or enclosing class to where the new \p type will be added.
* \param typeName Name by which the type will be known in Python.
* \param originalName Original C++ name of the type.
* \param type The new type to be initialized and added to the module.
* \param cppObjDtor Memory deallocation function for the C++ object held by \p type.
* Should not be used if the underlying C++ class has a private destructor.
* \param baseType Base type from whom the new \p type inherits.
* \param baseTypes Other base types from whom the new \p type inherits.
* \param isInnerClass Tells if the new \p type is an inner class (the default is that it isn't).
* If false then the \p enclosingObject is a module, otherwise it is another
* wrapper type.
* \returns true if the initialization went fine, false otherwise.
*/
LIBSHIBOKEN_API PyTypeObject *introduceWrapperType(PyObject *enclosingObject,
const char *typeName,
const char *originalName,
PyType_Spec *typeSpec,
ObjectDestructor cppObjDtor,
PyObject *bases,
unsigned wrapperFlags = 0);
/**
* Set the subtype init hook for a type.
*
* This hook will be invoked every time the user creates a sub-type inherited from a Shiboken based type.
* The hook gets 3 params, they are: The new type being created, args and kwds. The last two are the very
* same got from tp_new.
*/
LIBSHIBOKEN_API void setSubTypeInitHook(PyTypeObject *self, SubTypeInitHook func);
/**
* Get the user data previously set by Shiboken::Object::setTypeUserData
*/
LIBSHIBOKEN_API void *getTypeUserData(PyTypeObject *self);
LIBSHIBOKEN_API void setTypeUserData(PyTypeObject *self, void *userData, DeleteUserDataFunc d_func);
/**
* Return an instance of PyTypeObject for a C++ type name as determined by
* typeinfo().name().
* \param typeName Type name
* \since 5.12
*/
LIBSHIBOKEN_API PyTypeObject *typeForTypeName(const char *typeName);
/**
* Returns whether PyTypeObject has a special cast function (multiple inheritance)
* \param sbkType Sbk type
* \since 5.12
*/
LIBSHIBOKEN_API bool hasSpecialCastFunction(PyTypeObject *sbkType);
/// Returns whether a C++ pointer of \p baseType can be safely downcast
/// to \p targetType (base is a direct, single line base class of targetType).
/// (is a direct, single-line inheritance)
/// \param baseType Python type of base class
/// \param targetType Python type of derived class
/// \since 6.8
LIBSHIBOKEN_API bool canDowncastTo(PyTypeObject *baseType, PyTypeObject *targetType);
}
namespace Object {
/**
* Returns a string with information about the internal state of the instance object, useful for debug purposes.
*/
LIBSHIBOKEN_API std::string info(SbkObject *self);
/**
* Returns true if the object is an instance of a type created by the Shiboken generator.
*/
LIBSHIBOKEN_API bool checkType(PyObject *pyObj);
/**
* Returns true if this object type is an instance of an user defined type derived from an Shiboken type.
* \see Shiboken::ObjectType::isUserType
*/
LIBSHIBOKEN_API bool isUserType(PyObject *pyObj);
/**
* Generic function used to make ObjectType hashable, the C++ pointer is used as hash value.
*/
LIBSHIBOKEN_API Py_hash_t hash(PyObject *pyObj);
/**
* Find a child of given wrapper having same address having the specified type.
*/
LIBSHIBOKEN_API SbkObject *findColocatedChild(SbkObject *wrapper,
const PyTypeObject *instanceType);
/**
* Bind a C++ object to Python. Forwards to
* newObjectWithHeuristics(), newObjectForType() depending on \p isExactType.
* \param instanceType equivalent Python type for the C++ object.
* \param hasOwnership if true, Python will try to delete the underlying C++ object when there's no more refs.
* \param isExactType if false, Shiboken will use some heuristics to detect the correct Python type of this C++
* object, in any case you must provide \p instanceType, it'll be used as search starting point
* and as fallback.
* \param typeName If non-null, this will be used as helper to find the correct Python type for this object.
*/
LIBSHIBOKEN_API PyObject *newObject(PyTypeObject *instanceType,
void *cptr,
bool hasOwnership = true,
bool isExactType = false,
const char *typeName = nullptr);
/// Bind a C++ object to Python for polymorphic pointers. Calls
/// newObjectWithHeuristics() with an additional check for multiple
/// inheritance, in which case it will fall back to instanceType.
/// \param instanceType Equivalent Python type for the C++ object.
/// \param hasOwnership if true, Python will try to delete the underlying C++ object
/// when there's no more refs.
/// \param typeName If non-null, this will be used as helper to find the correct
/// Python type for this object (obtained by typeid().name().
LIBSHIBOKEN_API PyObject *newObjectForPointer(PyTypeObject *instanceType,
void *cptr,
bool hasOwnership = true,
const char *typeName = nullptr);
/// Bind a C++ object to Python using some heuristics to detect the correct
/// Python type of this C++ object. In any case \p instanceType must be provided;
/// it'll be used as search starting point and as fallback.
/// \param instanceType Equivalent Python type for the C++ object.
/// \param hasOwnership if true, Python will try to delete the underlying C++ object
/// C++ object when there are no more references.
/// when there's no more refs.
/// \param typeName If non-null, this will be used as helper to find the correct
/// Python type for this object (obtained by typeid().name().
LIBSHIBOKEN_API PyObject *newObjectWithHeuristics(PyTypeObject *instanceType,
void *cptr,
bool hasOwnership = true,
const char *typeName = nullptr);
/// Bind a C++ object to Python using the given type.
/// \param instanceType Equivalent Python type for the C++ object.
/// \param hasOwnership if true, Python will try to delete the underlying
/// C++ object when there are no more references.
LIBSHIBOKEN_API PyObject *newObjectForType(PyTypeObject *instanceType,
void *cptr, bool hasOwnership = true);
/**
* Changes the valid flag of a PyObject, invalid objects will raise an exception when someone tries to access it.
*/
LIBSHIBOKEN_API void setValidCpp(SbkObject *pyObj, bool value);
/**
* Tells shiboken the Python object \p pyObj has a C++ wrapper used to intercept virtual method calls.
*/
LIBSHIBOKEN_API void setHasCppWrapper(SbkObject *pyObj, bool value);
/**
* Return true if the Python object \p pyObj has a C++ wrapper used to intercept virtual method calls.
*/
LIBSHIBOKEN_API bool hasCppWrapper(SbkObject *pyObj);
/**
* Return true if the Python object was created by Python, false otherwise.
* \note This function was added to libshiboken only to be used by shiboken.wasCreatedByPython()
*/
LIBSHIBOKEN_API bool wasCreatedByPython(SbkObject *pyObj);
/**
* Call the C++ object destructor and invalidates the Python object.
* \note This function was added to libshiboken only to be used by shiboken.delete()
*/
LIBSHIBOKEN_API void callCppDestructors(SbkObject *pyObj);
/**
* Return true if the Python is responsible for deleting the underlying C++ object.
*/
LIBSHIBOKEN_API bool hasOwnership(SbkObject *pyObj);
/**
* Sets python as responsible to delete the underlying C++ object.
* \note You this overload only when the PyObject can be a sequence and you want to
* call this function for every item in the sequence.
* \see getOwnership(SbkObject *)
*/
LIBSHIBOKEN_API void getOwnership(PyObject *pyObj);
/**
* Sets python as responsible to delete the underlying C++ object.
*/
LIBSHIBOKEN_API void getOwnership(SbkObject *pyObj);
/**
* Release the ownership, so Python will not delete the underlying C++ object.
* \note You this overload only when the PyObject can be a sequence and you want to
* call this function for every item in the sequence.
* \see releaseOwnership(SbkObject *)
*/
LIBSHIBOKEN_API void releaseOwnership(PyObject *pyObj);
/**
* Release the ownership, so Python will not delete the underlying C++ object.
*/
LIBSHIBOKEN_API void releaseOwnership(SbkObject *pyObj);
/**
* Get the C++ pointer of type \p desiredType from a Python object.
*/
LIBSHIBOKEN_API void *cppPointer(SbkObject *pyObj, PyTypeObject *desiredType);
/**
* Return a list with all C++ pointers held from a Python object.
* \note This function was added to libshiboken only to be used by shiboken.getCppPointer()
*/
LIBSHIBOKEN_API std::vector<void *>cppPointers(SbkObject *pyObj);
/**
* Set the C++ pointer of type \p desiredType of a Python object.
*/
LIBSHIBOKEN_API bool setCppPointer(SbkObject *sbkObj, PyTypeObject *desiredType, void *cptr);
/**
* Returns false and sets a Python RuntimeError if the Python wrapper is not marked as valid.
*/
LIBSHIBOKEN_API bool isValid(PyObject *pyObj);
/**
* Returns false if the Python wrapper is not marked as valid.
* \param pyObj the object.
* \param throwPyError sets a Python RuntimeError when the object isn't valid.
*/
LIBSHIBOKEN_API bool isValid(SbkObject *pyObj, bool throwPyError = true);
/**
* Returns false if the Python wrapper is not marked as valid.
* \param pyObj the object.
* \param throwPyError sets a Python RuntimeError when the object isn't valid.
*/
LIBSHIBOKEN_API bool isValid(PyObject *pyObj, bool throwPyError);
/**
* Set the parent of \p child to \p parent.
* When an object dies, all their children, grandchildren, etc, are tagged as invalid.
* \param parent the parent object, if null, the child will have no parents.
* \param child the child.
*/
LIBSHIBOKEN_API void setParent(PyObject *parent, PyObject *child);
/**
* Remove this child from their parent, if any.
* \param child the child.
*/
LIBSHIBOKEN_API void removeParent(SbkObject *child, bool giveOwnershipBack = true, bool keepReferenc = false);
/**
* Mark the object as invalid
*/
LIBSHIBOKEN_API void invalidate(SbkObject *self);
/**
* Help function can be used to invalidate a sequence of object
**/
LIBSHIBOKEN_API void invalidate(PyObject *pyobj);
/**
* Make the object valid again
*/
LIBSHIBOKEN_API void makeValid(SbkObject *self);
/**
* Destroy any data in Shiboken structure and c++ pointer if the pyboject has the ownership
*/
LIBSHIBOKEN_API void destroy(SbkObject *self, void *cppData);
/**
* Set user data on type of \p wrapper.
* \param wrapper instance object, the user data will be set on his type
* \param userData the user data
* \param d_func a function used to delete the user data
*/
LIBSHIBOKEN_API void setTypeUserData(SbkObject *wrapper, void *userData, DeleteUserDataFunc d_func);
/**
* Get the user data previously set by Shiboken::Object::setTypeUserData
*/
LIBSHIBOKEN_API void *getTypeUserData(SbkObject *wrapper);
/**
* Increments the reference count of the referred Python object.
* A previous Python object in the same position identified by the 'key' parameter
* will have its reference counter decremented automatically when replaced.
* All the kept references should be decremented when the Python wrapper indicated by
* 'self' dies.
* No checking is done for any of the passed arguments, since it is meant to be used
* by generated code it is supposed that the generator is correct.
* \param self the wrapper instance that keeps references to other objects.
* \param key a key that identifies the C++ method signature and argument where the referred Object came from.
* \param referredObject the object whose reference is used by the self object.
*/
LIBSHIBOKEN_API void keepReference(SbkObject *self, const char *key, PyObject *referredObject, bool append = false);
/**
* Removes any reference previously added by keepReference function
* \param self the wrapper instance that keeps references to other objects.
* \param key a key that identifies the C++ method signature and argument from where the referred Object came.
* \param referredObject the object whose reference is used by the self object.
*/
LIBSHIBOKEN_API void removeReference(SbkObject *self, const char *key, PyObject *referredObject);
} // namespace Object
} // namespace Shiboken
#endif // BASEWRAPPER_H

View File

@@ -0,0 +1,172 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef BASEWRAPPER_P_H
#define BASEWRAPPER_P_H
#include "sbkpython.h"
#include "basewrapper.h"
#include <unordered_map>
#include <set>
#include <string>
#include <vector>
#include <iosfwd>
struct SbkObject;
struct SbkConverter;
namespace Shiboken
{
/**
* This mapping associates a method and argument of an wrapper object with the wrapper of
* said argument when it needs the binding to help manage its reference count.
*/
using RefCountMap = std::unordered_multimap<std::string, PyObject *> ;
/// Linked list of SbkBaseWrapper pointers
using ChildrenList = std::set<SbkObject *>;
/// Structure used to store information about object parent and children.
struct ParentInfo
{
/// Pointer to parent object.
SbkObject *parent = nullptr;
/// List of object children.
ChildrenList children;
/// has internal ref
bool hasWrapperRef = false;
};
} // namespace Shiboken
extern "C"
{
/**
* \internal
* Private data for SbkBaseWrapper
*/
struct SbkObjectPrivate
{
SbkObjectPrivate() noexcept = default;
SbkObjectPrivate(const SbkObjectPrivate &) = delete;
SbkObjectPrivate(SbkObjectPrivate &&o) = delete;
SbkObjectPrivate &operator=(const SbkObjectPrivate &) = delete;
SbkObjectPrivate &operator=(SbkObjectPrivate &&o) = delete;
/// Pointer to the C++ class.
void ** cptr;
/// True when Python is responsible for freeing the used memory.
unsigned int hasOwnership : 1;
/// This is true when the C++ class of the wrapped object has a virtual destructor AND was created by Python.
unsigned int containsCppWrapper : 1;
/// Marked as false when the object is lost to C++ and the binding can not know if it was deleted or not.
unsigned int validCppObject : 1;
/// Marked as true when the object constructor was called
unsigned int cppObjectCreated : 1;
/// PYSIDE-1470: Marked as true if this is the Q*Application singleton.
/// This bit allows app deletion from shiboken?.delete() .
unsigned int isQAppSingleton : 1;
/// Information about the object parents and children, may be null.
Shiboken::ParentInfo *parentInfo;
/// Manage reference count of objects that are referred to but not owned from.
Shiboken::RefCountMap *referredObjects;
~SbkObjectPrivate()
{
delete parentInfo;
parentInfo = nullptr;
delete referredObjects;
referredObjects = nullptr;
}
};
// TODO-CONVERTERS: to be deprecated/removed
/// The type behaviour was not defined yet
#define BEHAVIOUR_UNDEFINED 0
/// The type is a value type
#define BEHAVIOUR_VALUETYPE 1
/// The type is an object type
#define BEHAVIOUR_OBJECTTYPE 2
struct SbkObjectTypePrivate
{
SbkConverter *converter;
int *mi_offsets;
MultipleInheritanceInitFunction mi_init;
/// Special cast function, null if this class doesn't have multiple inheritance.
SpecialCastFunction mi_specialcast;
TypeDiscoveryFuncV2 type_discovery;
/// Pointer to a function responsible for deletion of the C++ instance calling the proper destructor.
ObjectDestructor cpp_dtor;
/// C++ name
char *original_name;
/// Type user data
void *user_data;
DeleteUserDataFunc d_func;
void (*subtype_init)(PyTypeObject *, PyObject *, PyObject *);
const char **propertyStrings;
const char **enumFlagInfo;
PyObject *enumFlagsDict;
PyObject *enumTypeDict;
/// True if this type holds two or more C++ instances, e.g.: a Python class which inherits from two C++ classes.
unsigned int is_multicpp : 1;
/// True if this type was defined by the user (a class written in Python inheriting
/// a class provided by a Shiboken binding).
unsigned int is_user_type : 1;
/// Tells is the type is a value type or an object-type, see BEHAVIOUR_ *constants.
unsigned int type_behaviour : 2;
unsigned int delete_in_main_thread : 1;
};
} // extern "C"
namespace Shiboken
{
/**
* \internal
* Data required to invoke a C++ destructor
*/
struct DestructorEntry
{
ObjectDestructor destructor;
void *cppInstance;
};
/**
* Utility function used to transform a PyObject that implements sequence protocol into a std::list.
**/
std::vector<SbkObject *> splitPyObject(PyObject *pyObj);
int getNumberOfCppBaseClasses(PyTypeObject *baseType);
namespace Object
{
/**
* Decrements the reference counters of every object referred by self.
* \param self the wrapper instance that keeps references to other objects.
*/
void clearReferences(SbkObject *self);
/**
* Destroy internal data
**/
void deallocData(SbkObject *self, bool doCleanup);
void _debugFormat(std::ostream &str, SbkObject *self);
} // namespace Object
inline PyTypeObject *pyType(SbkObject *sbo)
{
return Py_TYPE(reinterpret_cast<PyObject *>(sbo));
}
} // namespace Shiboken
#endif

View File

@@ -0,0 +1,96 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef BINDINGMANAGER_H
#define BINDINGMANAGER_H
#include "sbkpython.h"
#include "shibokenmacros.h"
#include <set>
#include <utility>
struct SbkObject;
namespace Shiboken
{
namespace Module {
struct TypeInitStruct;
}
struct DestructorEntry;
using ObjectVisitor = void (*)(SbkObject *, void *);
class LIBSHIBOKEN_API BindingManager
{
public:
BindingManager(const BindingManager &) = delete;
BindingManager(BindingManager &&) = delete;
BindingManager &operator=(const BindingManager &) = delete;
BindingManager &operator=(BindingManager &&) = delete;
static BindingManager &instance();
bool hasWrapper(const void *cptr, PyTypeObject *typeObject) const;
bool hasWrapper(const void *cptr) const;
void registerWrapper(SbkObject *pyObj, void *cptr);
void releaseWrapper(SbkObject *wrapper);
void runDeletionInMainThread();
void addToDeletionInMainThread(const DestructorEntry &);
SbkObject *retrieveWrapper(const void *cptr, PyTypeObject *typeObject) const;
SbkObject *retrieveWrapper(const void *cptr) const;
static PyObject *getOverride(SbkObject *wrapper, PyObject *pyMethodName);
void addClassInheritance(Module::TypeInitStruct *parent, Module::TypeInitStruct *child);
/// Try to find the correct type of cptr via type discovery knowing that it's at least
/// of type \p type. If a derived class is found, it returns a cptr cast to the type
/// (which may be different in case of multiple inheritance.
/// \param cptr a pointer to the instance of type \p type
/// \param type type of cptr
using TypeCptrPair = std::pair<PyTypeObject *, void *>;
TypeCptrPair findDerivedType(void *cptr, PyTypeObject *type) const;
/**
* Try to find the correct type of *cptr knowing that it's at least of type \p type.
* In case of multiple inheritance this function may change the contents of cptr.
* \param cptr a pointer to a pointer to the instance of type \p type
* \param type type of *cptr
* \warning This function is slow, use it only as last resort.
*/
[[deprecated]] PyTypeObject *resolveType(void **cptr, PyTypeObject *type);
std::set<PyObject *> getAllPyObjects();
/**
* Calls the function \p visitor for each object registered on binding manager.
* \note As various C++ pointers can point to the same PyObject due to multiple inheritance
* a PyObject can be called more than one time for each PyObject.
* \param visitor function called for each object.
* \param data user data passed as second argument to the visitor function.
*/
void visitAllPyObjects(ObjectVisitor visitor, void *data);
bool dumpTypeGraph(const char *fileName) const;
void dumpWrapperMap();
private:
~BindingManager();
BindingManager();
struct BindingManagerPrivate;
BindingManagerPrivate *m_d;
};
LIBSHIBOKEN_API bool callInheritedInit(PyObject *self, PyObject *args, PyObject *kwds,
const char *fullName);
LIBSHIBOKEN_API bool callInheritedInit(PyObject *self, PyObject *args, PyObject *kwds,
Module::TypeInitStruct typeStruct);
} // namespace Shiboken
#endif // BINDINGMANAGER_H

View File

@@ -0,0 +1,163 @@
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
/*
PSF LICENSE AGREEMENT FOR PYTHON 3.7.0
1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
the Individual or Organization ("Licensee") accessing and otherwise using Python
3.7.0 software in source or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python 3.7.0 alone or in any derivative
version, provided, however, that PSF's License Agreement and PSF's notice of
copyright, i.e., "Copyright © 2001-2018 Python Software Foundation; All Rights
Reserved" are retained in Python 3.7.0 alone or in any derivative version
prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on or
incorporates Python 3.7.0 or any part thereof, and wants to make the
derivative work available to others as provided herein, then Licensee hereby
agrees to include in any such work a brief summary of the changes made to Python
3.7.0.
4. PSF is making Python 3.7.0 available to Licensee on an "AS IS" basis.
PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF
EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
USE OF PYTHON 3.7.0 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.7.0
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.7.0, OR ANY DERIVATIVE
THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material breach of
its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any relationship
of agency, partnership, or joint venture between PSF and Licensee. This License
Agreement does not grant permission to use PSF trademarks or trade name in a
trademark sense to endorse or promote products or services of Licensee, or any
third party.
8. By copying, installing or otherwise using Python 3.7.0, Licensee agrees
to be bound by the terms and conditions of this License Agreement.
*/
#ifndef BUFFER_REENABLE_H
#define BUFFER_REENABLE_H
#include "sbkpython.h"
#include "shibokenmacros.h"
#ifdef Py_LIMITED_API
// The buffer interface has been added to limited API in 3.11, (abstract.h, PYSIDE-1960,
// except some internal structs).
# if Py_LIMITED_API < 0x030B0000
struct Pep_buffer
{
void *buf;
PyObject *obj; /* owned reference */
Py_ssize_t len;
Py_ssize_t itemsize; /* This is Py_ssize_t so it can be
pointed to by strides in simple case.*/
int readonly;
int ndim;
char *format;
Py_ssize_t *shape;
Py_ssize_t *strides;
Py_ssize_t *suboffsets;
void *internal;
};
using getbufferproc =int (*)(PyObject *, Pep_buffer *, int);
using releasebufferproc = void (*)(PyObject *, Pep_buffer *);
using Py_buffer = Pep_buffer;
# else // < 3.11
using Pep_buffer = Py_buffer;
# endif // >= 3.11
// The structs below are not part of the limited API.
struct PepBufferProcs
{
getbufferproc bf_getbuffer;
releasebufferproc bf_releasebuffer;
};
struct PepBufferType
{
PyVarObject ob_base;
void *skip[17];
PepBufferProcs *tp_as_buffer;
};
# if Py_LIMITED_API < 0x030B0000
/* Maximum number of dimensions */
#define PyBUF_MAX_NDIM 64
/* Flags for getting buffers */
#define PyBUF_SIMPLE 0
#define PyBUF_WRITABLE 0x0001
/* we used to include an E, backwards compatible alias */
#define PyBUF_WRITEABLE PyBUF_WRITABLE
#define PyBUF_FORMAT 0x0004
#define PyBUF_ND 0x0008
#define PyBUF_STRIDES (0x0010 | PyBUF_ND)
#define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES)
#define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES)
#define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES)
#define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)
#define PyBUF_CONTIG (PyBUF_ND | PyBUF_WRITABLE)
#define PyBUF_CONTIG_RO (PyBUF_ND)
#define PyBUF_STRIDED (PyBUF_STRIDES | PyBUF_WRITABLE)
#define PyBUF_STRIDED_RO (PyBUF_STRIDES)
#define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_WRITABLE | PyBUF_FORMAT)
#define PyBUF_RECORDS_RO (PyBUF_STRIDES | PyBUF_FORMAT)
#define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT)
#define PyBUF_FULL_RO (PyBUF_INDIRECT | PyBUF_FORMAT)
#define PyBUF_READ 0x100
#define PyBUF_WRITE 0x200
/* End buffer interface */
LIBSHIBOKEN_API PyObject *PyMemoryView_FromBuffer(Pep_buffer *info);
#define Py_buffer Pep_buffer
#define PyObject_CheckBuffer(obj) \
((PepType_AS_BUFFER(Py_TYPE(obj)) != NULL) && \
(PepType_AS_BUFFER(Py_TYPE(obj))->bf_getbuffer != NULL))
LIBSHIBOKEN_API int PyObject_GetBuffer(PyObject *ob, Pep_buffer *view, int flags);
LIBSHIBOKEN_API void PyBuffer_Release(Pep_buffer *view);
# endif // << 3.11
# define PepType_AS_BUFFER(type) \
reinterpret_cast<PepBufferType *>(type)->tp_as_buffer
using PyBufferProcs = PepBufferProcs;
#else // Py_LIMITED_API
using PepBufferProcs = PyBufferProcs;
# define PepType_AS_BUFFER(type) ((type)->tp_as_buffer)
#endif // !Py_LIMITED_API
#endif // BUFFER_REENABLE_H

View File

@@ -0,0 +1,33 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef GILSTATE_H
#define GILSTATE_H
#include <shibokenmacros.h>
#include "sbkpython.h"
namespace Shiboken
{
class LIBSHIBOKEN_API GilState
{
public:
GilState(const GilState &) = delete;
GilState(GilState &&) = delete;
GilState &operator=(const GilState &) = delete;
GilState &operator=(GilState &&) = delete;
explicit GilState(bool acquire=true);
~GilState();
void acquire();
void release();
void abandon();
private:
PyGILState_STATE m_gstate;
bool m_locked = false;
};
} // namespace Shiboken
#endif // GILSTATE_H

View File

@@ -0,0 +1,123 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef HELPER_H
#define HELPER_H
#include "sbkpython.h"
#include "shibokenmacros.h"
#include "autodecref.h"
#include <iosfwd>
#define SBK_UNUSED(x) (void)(x);
namespace Shiboken
{
/**
* It transforms a python sequence into two C variables, argc and argv.
* This function tries to find the application (script) name and put it into argv[0], if
* the application name can't be guessed, defaultAppName will be used.
*
* No memory is allocated is an error occur.
*
* \note argc must be a valid address.
* \note The argv array is allocated using new operator and each item is allocated using malloc.
* \returns True on sucess, false otherwise.
*/
LIBSHIBOKEN_API bool listToArgcArgv(PyObject *argList, int *argc, char ***argv, const char *defaultAppName = nullptr);
/// Delete a a list of arguments created by listToArgcArgv()
LIBSHIBOKEN_API void deleteArgv(int argc, char **argv);
/**
* Convert a python sequence into a heap-allocated array of ints.
*
* \returns The newly allocated array or NULL in case of error or empty sequence. Check with PyErr_Occurred
* if it was successfull.
*/
LIBSHIBOKEN_API int *sequenceToIntArray(PyObject *obj, bool zeroTerminated = false);
/// Fix a type name returned by typeid(t).name(), depending on compiler.
/// \returns Fixed name (allocated).
LIBSHIBOKEN_API const char *typeNameOf(const char *typeIdName);
/// Returns whether \a method is a compiled method (Nuitka).
LIBSHIBOKEN_API bool isCompiledMethod(PyObject *method);
/**
* Creates and automatically deallocates C++ arrays.
*/
template<class T>
class ArrayPointer
{
public:
ArrayPointer(const ArrayPointer &) = delete;
ArrayPointer(ArrayPointer &&) = delete;
ArrayPointer &operator=(const ArrayPointer &) = delete;
ArrayPointer &operator=(ArrayPointer &&) = delete;
explicit ArrayPointer(Py_ssize_t size) : data(new T[size]) {}
T &operator[](Py_ssize_t pos) { return data[pos]; }
operator T *() const { return data; }
~ArrayPointer() { delete[] data; }
private:
T *data;
};
template <class T>
using AutoArrayPointer = ArrayPointer<T>; // deprecated
using ThreadId = unsigned long long;
LIBSHIBOKEN_API ThreadId currentThreadId();
LIBSHIBOKEN_API ThreadId mainThreadId();
LIBSHIBOKEN_API int pyVerbose();
/**
* An utility function used to call PyErr_WarnEx with a formatted message.
*/
LIBSHIBOKEN_API int warning(PyObject *category, int stacklevel, const char *format, ...);
struct LIBSHIBOKEN_API debugPyObject
{
explicit debugPyObject(PyObject *o);
PyObject *m_object;
};
struct LIBSHIBOKEN_API debugSbkObject
{
explicit debugSbkObject(SbkObject *o);
SbkObject *m_object;
};
struct LIBSHIBOKEN_API debugPyTypeObject
{
explicit debugPyTypeObject(PyTypeObject *o);
PyTypeObject *m_object;
};
struct debugPyBuffer;
struct debugPyArrayObject
{
explicit debugPyArrayObject(PyObject *object) : m_object(object) {}
PyObject *m_object;
};
LIBSHIBOKEN_API std::ostream &operator<<(std::ostream &str, const debugPyObject &o);
LIBSHIBOKEN_API std::ostream &operator<<(std::ostream &str, const debugSbkObject &o);
LIBSHIBOKEN_API std::ostream &operator<<(std::ostream &str, const debugPyTypeObject &o);
LIBSHIBOKEN_API std::ostream &operator<<(std::ostream &str, const debugPyBuffer &b);
LIBSHIBOKEN_API std::ostream &operator<<(std::ostream &str, const debugPyArrayObject &b);
LIBSHIBOKEN_API std::ios_base &debugVerbose(std::ios_base &s);
LIBSHIBOKEN_API std::ios_base &debugBrief(std::ios_base &s);
} // namespace Shiboken
#endif // HELPER_H

View File

@@ -0,0 +1,91 @@
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PEP384EXT_H
#define PEP384EXT_H
#include "pep384impl.h"
/// Returns the allocator slot of the PyTypeObject.
inline allocfunc PepExt_Type_GetAllocSlot(PyTypeObject *t)
{
return reinterpret_cast<allocfunc>(PepType_GetSlot(t, Py_tp_alloc));
}
/// Invokes the allocator slot of the PyTypeObject.
template <class Type>
inline Type *PepExt_TypeCallAlloc(PyTypeObject *t, Py_ssize_t nitems)
{
PyObject *result = PepExt_Type_GetAllocSlot(t)(t, nitems);
return reinterpret_cast<Type *>(result);
}
/// Returns the getattro slot of the PyTypeObject.
inline getattrofunc PepExt_Type_GetGetAttroSlot(PyTypeObject *t)
{
return reinterpret_cast<getattrofunc>(PepType_GetSlot(t, Py_tp_getattro));
}
/// Returns the setattro slot of the PyTypeObject.
inline setattrofunc PepExt_Type_GetSetAttroSlot(PyTypeObject *t)
{
return reinterpret_cast<setattrofunc>(PepType_GetSlot(t, Py_tp_setattro));
}
/// Returns the descr_get slot of the PyTypeObject.
inline descrgetfunc PepExt_Type_GetDescrGetSlot(PyTypeObject *t)
{
return reinterpret_cast<descrgetfunc>(PepType_GetSlot(t, Py_tp_descr_get));
}
/// Invokes the descr_get slot of the PyTypeObject.
inline PyObject *PepExt_Type_CallDescrGet(PyObject *self, PyObject *obj, PyObject *type)
{
return PepExt_Type_GetDescrGetSlot(Py_TYPE(self))(self, obj, type);
}
/// Returns the descr_set slot of the PyTypeObject.
inline descrsetfunc PepExt_Type_GetDescrSetSlot(PyTypeObject *t)
{
return reinterpret_cast<descrsetfunc>(PepType_GetSlot(t, Py_tp_descr_set));
}
/// Returns the call slot of the PyTypeObject.
inline ternaryfunc PepExt_Type_GetCallSlot(PyTypeObject *t)
{
return reinterpret_cast<ternaryfunc>(PepType_GetSlot(t, Py_tp_call));
}
/// Returns the new slot of the PyTypeObject.
inline newfunc PepExt_Type_GetNewSlot(PyTypeObject *t)
{
return reinterpret_cast<newfunc>(PepType_GetSlot(t, Py_tp_new));
}
/// Returns the init slot of the PyTypeObject.
inline initproc PepExt_Type_GetInitSlot(PyTypeObject *t)
{
return reinterpret_cast<initproc>(PepType_GetSlot(t, Py_tp_init));
}
/// Returns the free slot of the PyTypeObject.
inline freefunc PepExt_Type_GetFreeSlot(PyTypeObject *t)
{
return reinterpret_cast<freefunc>(PepType_GetSlot(t, Py_tp_free));
}
/// Invokes the free slot of the PyTypeObject.
inline void PepExt_TypeCallFree(PyTypeObject *t, void *object)
{
PepExt_Type_GetFreeSlot(t)(object);
}
/// Invokes the free slot of the PyTypeObject.
inline void PepExt_TypeCallFree(PyObject *object)
{
PepExt_Type_GetFreeSlot(Py_TYPE(object))(object);
}
LIBSHIBOKEN_API bool PepExt_Weakref_IsAlive(PyObject *weakRef);
#endif // PEP384EXT_H

View File

@@ -0,0 +1,533 @@
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PEP384IMPL_H
#define PEP384IMPL_H
#include "sbkpython.h"
#include "shibokenmacros.h"
extern "C"
{
/*****************************************************************************
*
* RESOLVED: object.h
*
*/
#ifdef Py_LIMITED_API
// Why the hell is this useful debugging function not allowed?
// BTW: When used, it breaks on Windows, intentionally!
LIBSHIBOKEN_API void _PyObject_Dump(PyObject *);
#endif
/*
* There are a few structures that are needed, but cannot be used without
* breaking the API. We use some heuristics to get those fields anyway
* and validate that we really found them, see pep384impl.cpp .
*/
#ifdef Py_LIMITED_API
/*
* These are the type object fields that we use.
* We will verify that they never change.
* The unused fields are intentionally named as "void *Xnn" because
* the chance is smaller to forget to validate a field.
* When we need more fields, we replace it back and add it to the
* validation.
*/
typedef struct _typeobject {
PyVarObject ob_base;
const char *tp_name;
Py_ssize_t tp_basicsize;
void *X03; // Py_ssize_t tp_itemsize;
#ifdef PEP384_INTERN
destructor tp_dealloc;
#else
destructor X04;
#endif
void *X05; // Py_ssize_t tp_vectorcall_offset;
void *X06; // getattrfunc tp_getattr;
void *X07; // setattrfunc tp_setattr;
void *X08; // PyAsyncMethods *tp_as_async;
#ifdef PEP384_INTERN
reprfunc tp_repr;
#else
reprfunc X09;
#endif
void *X10; // PyNumberMethods *tp_as_number;
void *X11; // PySequenceMethods *tp_as_sequence;
void *X12; // PyMappingMethods *tp_as_mapping;
void *X13; // hashfunc tp_hash;
#ifdef PEP384_INTERN
ternaryfunc tp_call;
#else
ternaryfunc X14;
#endif
reprfunc tp_str; // Only used for PEP384_INTERN and a shiboken test
getattrofunc tp_getattro;
setattrofunc tp_setattro;
void *X18; // PyBufferProcs *tp_as_buffer;
unsigned long tp_flags;
void *X20; // const char *tp_doc;
#ifdef PEP384_INTERN
traverseproc tp_traverse;
inquiry tp_clear;
#else
traverseproc X21;
inquiry X22;
#endif
void *X23; // richcmpfunc tp_richcompare;
Py_ssize_t tp_weaklistoffset;
void *X25; // getiterfunc tp_iter;
#ifdef PEP384_INTERN
iternextfunc tp_iternext;
#else
iternextfunc X26;
#endif
struct PyMethodDef *tp_methods;
struct PyMemberDef *tp_members;
struct PyGetSetDef *tp_getset;
struct _typeobject *tp_base;
#ifdef PEP384_INTERN
PyObject *tp_dict;
descrgetfunc tp_descr_get;
descrsetfunc tp_descr_set;
#else
void *X31;
descrgetfunc X32;
descrsetfunc X33;
#endif
Py_ssize_t tp_dictoffset;
#ifdef PEP384_INTERN
initproc tp_init;
allocfunc tp_alloc;
#else
initproc X39;
allocfunc X40;
#endif
newfunc tp_new;
#ifdef PEP384_INTERN
freefunc tp_free;
inquiry tp_is_gc; /* For PyObject_IS_GC */
#else
freefunc X41;
inquiry X42; /* For PyObject_IS_GC */
#endif
PyObject *tp_bases;
PyObject *tp_mro; /* method resolution order */
} PyTypeObject;
#ifndef PyObject_IS_GC
/* Test if an object has a GC head */
#define PyObject_IS_GC(o) \
(PyType_IS_GC(Py_TYPE(o)) \
&& (Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o)))
#endif
LIBSHIBOKEN_API PyObject *_PepType_Lookup(PyTypeObject *type, PyObject *name);
#else // Py_LIMITED_API
#define _PepType_Lookup(type, name) _PyType_Lookup(type, name)
#endif // Py_LIMITED_API
/// PYSIDE-939: We need the runtime version, given major << 16 + minor << 8 + micro
LIBSHIBOKEN_API long _PepRuntimeVersion();
/*****************************************************************************
*
* PYSIDE-535: Implement a clean type extension for PyPy
*
*/
struct SbkObjectTypePrivate;
LIBSHIBOKEN_API SbkObjectTypePrivate *PepType_SOTP(PyTypeObject *type);
LIBSHIBOKEN_API void PepType_SOTP_delete(PyTypeObject *type);
struct SbkEnumType;
struct SbkEnumTypePrivate;
LIBSHIBOKEN_API SbkEnumTypePrivate *PepType_SETP(SbkEnumType *type);
LIBSHIBOKEN_API void PepType_SETP_delete(SbkEnumType *enumType);
struct PySideQFlagsType;
struct SbkQFlagsTypePrivate;
/*****************************************************************************/
// functions used everywhere
/// (convenience) Return the unqualified type name
LIBSHIBOKEN_API const char *PepType_GetNameStr(PyTypeObject *type);
/// (convenience) Return the fully qualified type name(PepType_GetFullyQualifiedNameStr())
/// as C-string
LIBSHIBOKEN_API const char *PepType_GetFullyQualifiedNameStr(PyTypeObject *type);
LIBSHIBOKEN_API PyObject *Pep_GetPartialFunction(void);
/*****************************************************************************
*
* RESOLVED: pydebug.h
*
*/
#ifdef Py_LIMITED_API
/*
* We have no direct access to Py_VerboseFlag because debugging is not
* supported. The python developers are partially a bit too rigorous.
* Instead, we compute the value and use a function call macro.
* Was before: extern LIBSHIBOKEN_API int Py_VerboseFlag;
*/
LIBSHIBOKEN_API int Pep_GetFlag(const char *name);
LIBSHIBOKEN_API int Pep_GetVerboseFlag(void);
#endif
#if (defined(Py_LIMITED_API) && Py_LIMITED_API < 0x030C0000) || PY_VERSION_HEX < 0x030C0000
# define PEP_OLD_ERR_API
#endif
// pyerrors.h
#ifdef PEP_OLD_ERR_API
LIBSHIBOKEN_API PyObject *PepErr_GetRaisedException();
LIBSHIBOKEN_API PyObject *PepException_GetArgs(PyObject *ex);
LIBSHIBOKEN_API void PepException_SetArgs(PyObject *ex, PyObject *args);
#else
inline PyObject *PepErr_GetRaisedException() { return PyErr_GetRaisedException(); }
inline PyObject *PepException_GetArgs(PyObject *ex) { return PyException_GetArgs(ex); }
inline void PepException_SetArgs(PyObject *ex, PyObject *args)
{ PyException_SetArgs(ex, args); }
#endif
/*****************************************************************************
*
* RESOLVED: unicodeobject.h
*
*/
///////////////////////////////////////////////////////////////////////
//
// PYSIDE-813: About The Length Of Unicode Objects
// -----------------------------------------------
//
// In Python 2 and before Python 3.3, the macro PyUnicode_GET_SIZE
// worked fine and really like a macro.
//
// Meanwhile, the unicode objects have changed their layout very much,
// and the former cheap macro call has become a real function call
// that converts objects and needs PyMemory.
//
// That is not only inefficient, but also requires the GIL!
// This problem was visible by debug Python and qdatastream_test.py .
// It was found while fixing the refcount problem of PYSIDE-813 which
// needed a debug Python.
//
// Unfortunately, we cannot ask this at runtime
// #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
// FIXME: Python 3.10: Replace _PepUnicode_AsString by PyUnicode_AsUTF8
#ifdef Py_LIMITED_API
LIBSHIBOKEN_API const char *_PepUnicode_AsString(PyObject *);
enum PepUnicode_Kind {
#if PY_VERSION_HEX < 0x030C0000
PepUnicode_WCHAR_KIND = 0,
#endif
PepUnicode_1BYTE_KIND = 1,
PepUnicode_2BYTE_KIND = 2,
PepUnicode_4BYTE_KIND = 4
};
LIBSHIBOKEN_API int _PepUnicode_KIND(PyObject *);
LIBSHIBOKEN_API int _PepUnicode_IS_ASCII(PyObject *str);
LIBSHIBOKEN_API int _PepUnicode_IS_COMPACT(PyObject *str);
LIBSHIBOKEN_API void *_PepUnicode_DATA(PyObject *str);
#else
enum PepUnicode_Kind {
#if PY_VERSION_HEX < 0x030C0000
PepUnicode_WCHAR_KIND = PyUnicode_WCHAR_KIND,
#endif
PepUnicode_1BYTE_KIND = PyUnicode_1BYTE_KIND,
PepUnicode_2BYTE_KIND = PyUnicode_2BYTE_KIND,
PepUnicode_4BYTE_KIND = PyUnicode_4BYTE_KIND
};
#define _PepUnicode_AsString PyUnicode_AsUTF8
#define _PepUnicode_KIND PyUnicode_KIND
#define _PepUnicode_DATA PyUnicode_DATA
#define _PepUnicode_IS_COMPACT PyUnicode_IS_COMPACT
#define _PepUnicode_IS_ASCII PyUnicode_IS_ASCII
#endif
/*****************************************************************************
*
* RESOLVED: methodobject.h
*
*/
#ifdef Py_LIMITED_API
using PyCFunctionObject = struct _pycfunc;
#define PepCFunction_GET_NAMESTR(func) \
_PepUnicode_AsString(PyObject_GetAttrString((PyObject *)func, "__name__"))
#else
#define PepCFunction_GET_NAMESTR(func) \
(reinterpret_cast<const PyCFunctionObject *>(func)->m_ml->ml_name)
#endif
/*****************************************************************************
*
* RESOLVED: pythonrun.h
*
*/
#ifdef Py_LIMITED_API
LIBSHIBOKEN_API PyObject *PyRun_String(const char *, int, PyObject *, PyObject *);
#endif
/*****************************************************************************
*
* RESOLVED: funcobject.h
*
*/
#ifdef Py_LIMITED_API
typedef struct _func PyFunctionObject;
extern LIBSHIBOKEN_API PyTypeObject *PepFunction_TypePtr;
LIBSHIBOKEN_API PyObject *PepFunction_Get(PyObject *, const char *);
#define PyFunction_Check(op) (Py_TYPE(op) == PepFunction_TypePtr)
#define PyFunction_GET_CODE(func) PyFunction_GetCode(func)
#define PyFunction_GetCode(func) PepFunction_Get((PyObject *)func, "__code__")
#define PepFunction_GetName(func) PepFunction_Get((PyObject *)func, "__name__")
#else
#define PepFunction_TypePtr (&PyFunction_Type)
#define PepFunction_GetName(func) (((PyFunctionObject *)func)->func_name)
#endif
/*****************************************************************************
*
* RESOLVED: classobject.h
*
*/
#ifdef Py_LIMITED_API
typedef struct _meth PyMethodObject;
extern LIBSHIBOKEN_API PyTypeObject *PepMethod_TypePtr;
LIBSHIBOKEN_API PyObject *PyMethod_New(PyObject *, PyObject *);
LIBSHIBOKEN_API PyObject *PyMethod_Function(PyObject *);
LIBSHIBOKEN_API PyObject *PyMethod_Self(PyObject *);
#define PyMethod_Check(op) ((op)->ob_type == PepMethod_TypePtr)
#define PyMethod_GET_SELF(op) PyMethod_Self(op)
#define PyMethod_GET_FUNCTION(op) PyMethod_Function(op)
#endif
/*****************************************************************************
*
* RESOLVED: code.h
*
*/
#ifdef Py_LIMITED_API
/* Bytecode object */
// we have to grab the code object from python
typedef struct _code PepCodeObject;
LIBSHIBOKEN_API int PepCode_Get(PepCodeObject *co, const char *name);
LIBSHIBOKEN_API int PepCode_Check(PyObject *o);
# define PepCode_GET_FLAGS(o) PepCode_Get(o, "co_flags")
# define PepCode_GET_ARGCOUNT(o) PepCode_Get(o, "co_argcount")
LIBSHIBOKEN_API PyObject *PepFunction_GetDefaults(PyObject *function);
/* Masks for co_flags above */
# define CO_OPTIMIZED 0x0001
# define CO_NEWLOCALS 0x0002
# define CO_VARARGS 0x0004
# define CO_VARKEYWORDS 0x0008
# define CO_NESTED 0x0010
# define CO_GENERATOR 0x0020
#else
# define PepCodeObject PyCodeObject
# define PepCode_GET_FLAGS(o) ((o)->co_flags)
# define PepCode_GET_ARGCOUNT(o) ((o)->co_argcount)
# define PepCode_Check PyCode_Check
# ifdef PYPY_VERSION
LIBSHIBOKEN_API PyObject *PepFunction_GetDefaults(PyObject *function);
# else
# define PepFunction_GetDefaults PyFunction_GetDefaults
# endif
#endif
/*****************************************************************************
*
* RESOLVED: datetime.h
*
*/
#ifdef Py_LIMITED_API
LIBSHIBOKEN_API int PyDateTime_Get(PyObject *ob, const char *name);
#define PyDateTime_GetYear(o) PyDateTime_Get(o, "year")
#define PyDateTime_GetMonth(o) PyDateTime_Get(o, "month")
#define PyDateTime_GetDay(o) PyDateTime_Get(o, "day")
#define PyDateTime_GetHour(o) PyDateTime_Get(o, "hour")
#define PyDateTime_GetMinute(o) PyDateTime_Get(o, "minute")
#define PyDateTime_GetSecond(o) PyDateTime_Get(o, "second")
#define PyDateTime_GetMicrosecond(o) PyDateTime_Get(o, "microsecond")
#define PyDateTime_GetFold(o) PyDateTime_Get(o, "fold")
#define PyDateTime_GET_YEAR(o) PyDateTime_GetYear(o)
#define PyDateTime_GET_MONTH(o) PyDateTime_GetMonth(o)
#define PyDateTime_GET_DAY(o) PyDateTime_GetDay(o)
#define PyDateTime_DATE_GET_HOUR(o) PyDateTime_GetHour(o)
#define PyDateTime_DATE_GET_MINUTE(o) PyDateTime_GetMinute(o)
#define PyDateTime_DATE_GET_SECOND(o) PyDateTime_GetSecond(o)
#define PyDateTime_DATE_GET_MICROSECOND(o) PyDateTime_GetMicrosecond(o)
#define PyDateTime_DATE_GET_FOLD(o) PyDateTime_GetFold(o)
#define PyDateTime_TIME_GET_HOUR(o) PyDateTime_GetHour(o)
#define PyDateTime_TIME_GET_MINUTE(o) PyDateTime_GetMinute(o)
#define PyDateTime_TIME_GET_SECOND(o) PyDateTime_GetSecond(o)
#define PyDateTime_TIME_GET_MICROSECOND(o) PyDateTime_GetMicrosecond(o)
#define PyDateTime_TIME_GET_FOLD(o) PyDateTime_GetFold(o)
/* Define structure slightly similar to C API. */
typedef struct {
PyObject *module;
/* type objects */
PyTypeObject *DateType;
PyTypeObject *DateTimeType;
PyTypeObject *TimeType;
PyTypeObject *DeltaType;
PyTypeObject *TZInfoType;
} datetime_struc;
LIBSHIBOKEN_API datetime_struc *init_DateTime(void);
#define PyDateTime_IMPORT PyDateTimeAPI = init_DateTime()
extern LIBSHIBOKEN_API datetime_struc *PyDateTimeAPI;
#define PyDate_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateType)
#define PyDateTime_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateTimeType)
#define PyTime_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->TimeType)
LIBSHIBOKEN_API PyObject *PyDate_FromDate(int year, int month, int day);
LIBSHIBOKEN_API PyObject *PyDateTime_FromDateAndTime(
int year, int month, int day, int hour, int min, int sec, int usec);
LIBSHIBOKEN_API PyObject *PyTime_FromTime(
int hour, int minute, int second, int usecond);
#endif /* Py_LIMITED_API */
/*****************************************************************************
*
* Extra support for name mangling
*
*/
// PYSIDE-772: This function supports the fix, but is not meant as public.
LIBSHIBOKEN_API PyObject *_Pep_PrivateMangle(PyObject *self, PyObject *name);
/*****************************************************************************
*
* Extra support for signature.cpp
*
*/
#ifdef Py_LIMITED_API
extern LIBSHIBOKEN_API PyTypeObject *PepStaticMethod_TypePtr;
LIBSHIBOKEN_API PyObject *PyStaticMethod_New(PyObject *callable);
#else
#define PepStaticMethod_TypePtr &PyStaticMethod_Type
#endif
#ifdef PYPY_VERSION
extern LIBSHIBOKEN_API PyTypeObject *PepBuiltinMethod_TypePtr;
#endif
// Although not PEP specific, we resolve this similar issue, here:
#define PepMethodDescr_TypePtr &PyMethodDescr_Type
/*****************************************************************************
*
* Newly introduced convenience functions
*
* This is not defined if Py_LIMITED_API is defined.
*/
// Evaluate a script and return the variable `result`
LIBSHIBOKEN_API PyObject *PepRun_GetResult(const char *command);
// Call PyType_Type.tp_new returning a PyType object.
LIBSHIBOKEN_API PyTypeObject *PepType_Type_tp_new(PyTypeObject *metatype,
PyObject *args,
PyObject *kwds);
/*****************************************************************************
*
* Runtime support for Python 3.8 incompatibilities
*
*/
#ifndef Py_TPFLAGS_METHOD_DESCRIPTOR
/* Objects behave like an unbound method */
#define Py_TPFLAGS_METHOD_DESCRIPTOR (1UL << 17)
#endif
/*****************************************************************************
*
* Runtime support for Python 3.12 incompatibility
*
*/
LIBSHIBOKEN_API PyObject *PepType_GetDict(PyTypeObject *type);
// This function does not exist as PyType_SetDict. But because tp_dict
// is no longer considered to be accessible, we treat it as such.
LIBSHIBOKEN_API int PepType_SetDict(PyTypeObject *type, PyObject *dict);
LIBSHIBOKEN_API void *PepType_GetSlot(PyTypeObject *type, int aSlot);
// Runtime support for Python 3.13 stable ABI
// Return dictionary of the global variables in the current execution frame
LIBSHIBOKEN_API PyObject *PepEval_GetFrameGlobals();
// Return a dictionary of the builtins in the current execution frame
LIBSHIBOKEN_API PyObject *PepEval_GetFrameBuiltins();
LIBSHIBOKEN_API int PepModule_AddType(PyObject *module, PyTypeObject *type);
LIBSHIBOKEN_API int PepModule_Add(PyObject *module, const char *name, PyObject *value);
/*****************************************************************************
*
* Module Initialization
*
*/
LIBSHIBOKEN_API void Pep384_Init(void);
} // extern "C"
#endif // PEP384IMPL_H

View File

@@ -0,0 +1,86 @@
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef PYOBJECTHOLDER_H
#define PYOBJECTHOLDER_H
#include "sbkpython.h"
#include <cassert>
#include <utility>
namespace Shiboken
{
/// PyObjectHolder holds a PyObject pointer, keeping a reference decrementing
/// its reference counter when destroyed. It makes sure to hold the GIL when
/// releasing. It implements copy/move semantics and is mainly intended as a
/// base class for functors holding a callable which can be passed around and
/// stored in containers or moved from freely.
/// For one-shot functors, release() can be invoked after the call.
class PyObjectHolder
{
public:
PyObjectHolder() noexcept = default;
/// PyObjectHolder constructor.
/// \param pyobj A reference to a Python object
explicit PyObjectHolder(PyObject *pyObj) noexcept : m_pyObj(pyObj)
{
assert(pyObj != nullptr);
Py_INCREF(m_pyObj);
}
PyObjectHolder(const PyObjectHolder &o) noexcept : m_pyObj(o.m_pyObj)
{
Py_XINCREF(m_pyObj);
}
PyObjectHolder &operator=(const PyObjectHolder &o) noexcept
{
if (this != &o) {
m_pyObj = o.m_pyObj;
Py_XINCREF(m_pyObj);
}
return *this;
}
PyObjectHolder(PyObjectHolder &&o) noexcept : m_pyObj{std::exchange(o.m_pyObj, nullptr)} {}
PyObjectHolder &operator=(PyObjectHolder &&o) noexcept
{
m_pyObj = std::exchange(o.m_pyObj, nullptr);
return *this;
}
/// Decref the python reference
~PyObjectHolder() { release(); }
[[nodiscard]] bool isNull() const { return m_pyObj == nullptr; }
[[nodiscard]] operator bool() const { return m_pyObj != nullptr; }
/// Returns the pointer of the Python object being held.
[[nodiscard]] PyObject *object() const { return m_pyObj; }
[[nodiscard]] operator PyObject *() const { return m_pyObj; }
[[nodiscard]] PyObject *operator->() { return m_pyObj; }
protected:
void release()
{
if (m_pyObj != nullptr) {
assert(Py_IsInitialized());
auto gstate = PyGILState_Ensure();
Py_DECREF(m_pyObj);
PyGILState_Release(gstate);
m_pyObj = nullptr;
}
}
private:
PyObject *m_pyObj = nullptr;
};
} // namespace Shiboken
#endif // PYOBJECTHOLDER_H

View File

@@ -0,0 +1,136 @@
// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKARRAYCONVERTERS_H
#define SBKARRAYCONVERTERS_H
#include "sbkpython.h"
#include "shibokenmacros.h"
extern "C" {
struct SbkArrayConverter;
}
namespace Shiboken::Conversions {
enum : int {
SBK_UNIMPLEMENTED_ARRAY_IDX,
SBK_DOUBLE_ARRAY_IDX,
SBK_FLOAT_ARRAY_IDX,
SBK_SHORT_ARRAY_IDX,
SBK_UNSIGNEDSHORT_ARRAY_IDX,
SBK_INT_ARRAY_IDX,
SBK_UNSIGNEDINT_ARRAY_IDX,
SBK_LONGLONG_ARRAY_IDX,
SBK_UNSIGNEDLONGLONG_ARRAY_IDX,
SBK_ARRAY_IDX_SIZE
};
/**
* ArrayHandle is the type expected by shiboken6's array converter
* functions. It provides access to array data which it may own
* (in the case of conversions from PySequence) or a flat pointer
* to internal data (in the case of array modules like numpy).
*/
template <class T>
class ArrayHandle
{
public:
ArrayHandle(const ArrayHandle &) = delete;
ArrayHandle& operator=(const ArrayHandle &) = delete;
ArrayHandle(ArrayHandle &&) = delete;
ArrayHandle& operator=(ArrayHandle &&) = delete;
ArrayHandle() = default;
~ArrayHandle() { destroy(); }
void allocate(Py_ssize_t size);
void setData(T *d, size_t size);
size_t size() const { return m_size; }
T *data() const { return m_data; }
operator T *() const { return m_data; }
private:
void destroy();
T *m_data = nullptr;
Py_ssize_t m_size = 0;
bool m_owned = false;
};
/**
* Similar to ArrayHandle for fixed size 2 dimensional arrays.
* columns is the size of the last dimension
* It only has a setData() methods since it will be used for numpy only.
*/
template <class T, int columns>
class Array2Handle
{
public:
using RowType = T[columns];
Array2Handle() = default;
operator RowType *() const { return m_rows; }
void setData(RowType *d) { m_rows = d; }
private:
RowType *m_rows = nullptr;
};
/// Returns the converter for an array type.
LIBSHIBOKEN_API SbkArrayConverter *arrayTypeConverter(int index, int dimension = 1);
template <class T>
struct ArrayTypeIndex{
enum : int { index = SBK_UNIMPLEMENTED_ARRAY_IDX };
};
template <> struct ArrayTypeIndex<double> { enum : int { index = SBK_DOUBLE_ARRAY_IDX }; };
template <> struct ArrayTypeIndex<float> { enum : int { index = SBK_FLOAT_ARRAY_IDX };};
template <> struct ArrayTypeIndex<short> { enum : int { index = SBK_SHORT_ARRAY_IDX };};
template <> struct ArrayTypeIndex<unsigned short> { enum : int { index = SBK_UNSIGNEDSHORT_ARRAY_IDX };};
template <> struct ArrayTypeIndex<int> { enum : int { index = SBK_INT_ARRAY_IDX };};
template <> struct ArrayTypeIndex<unsigned> { enum : int { index = SBK_UNSIGNEDINT_ARRAY_IDX };};
template <> struct ArrayTypeIndex<long long> { enum : int { index = SBK_LONGLONG_ARRAY_IDX };};
template <> struct ArrayTypeIndex<unsigned long long> { enum : int { index = SBK_UNSIGNEDLONGLONG_ARRAY_IDX };};
template<typename T> SbkArrayConverter *ArrayTypeConverter(int dimension)
{ return arrayTypeConverter(ArrayTypeIndex<T>::index, dimension); }
// ArrayHandle methods
template<class T>
void ArrayHandle<T>::allocate(Py_ssize_t size)
{
destroy();
m_data = new T[size];
m_size = size;
m_owned = true;
}
template<class T>
void ArrayHandle<T>::setData(T *d, size_t size)
{
destroy();
m_data = d;
m_size = size;
m_owned = false;
}
template<class T>
void ArrayHandle<T>::destroy()
{
if (m_owned)
delete [] m_data;
m_data = nullptr;
m_size = 0;
m_owned = false;
}
} // namespace Shiboken::Conversions
#endif // SBKARRAYCONVERTERS_H

View File

@@ -0,0 +1,43 @@
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBK_BINDINGUTILS
#define SBK_BINDINGUTILS
#include "sbkpython.h"
#include "shibokenmacros.h"
namespace Shiboken {
struct AutoDecRef;
/// Maps a keyword argument by name to its parameter index
struct ArgumentNameIndexMapping
{
const char *name;
int index;
};
/// Function binding helper: Parse the keyword arguments in dict \a kwds
/// according to \a mapping (name->index) and store them in array \a pyArgs
/// under their index. Fails if an entry is missing or duplicate entries
/// occur.
LIBSHIBOKEN_API bool
parseKeywordArguments(PyObject *kwds,
const ArgumentNameIndexMapping *mapping, size_t size,
Shiboken::AutoDecRef &errInfo, PyObject **pyArgs);
/// Function binding helper: Parse the keyword arguments of a QObject constructor
/// in dict \a kwds according to \a mapping (name->index) and store them in array
/// \a pyArgs under their index. Fails if duplicate entries occur. Unmapped entries
/// (QObject properties) are stored in a dict in errInfo for further processing.
LIBSHIBOKEN_API bool
parseConstructorKeywordArguments(PyObject *kwds,
const ArgumentNameIndexMapping *mapping, size_t size,
Shiboken::AutoDecRef &errInfo, PyObject **pyArgs);
/// Returns whether we are running in compiled mode (Nuitka).
LIBSHIBOKEN_API bool isCompiled();
} // namespace Shiboken
#endif // SBK_BINDINGUTILS

View File

@@ -0,0 +1,283 @@
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBK_CONTAINER_H
#define SBK_CONTAINER_H
#include "sbkpython.h"
#include "shibokenmacros.h"
#include "shibokenbuffer.h"
#include <algorithm>
#include <iterator>
#include <optional>
#include <utility>
// Opaque container helpers
extern "C"
{
struct LIBSHIBOKEN_API ShibokenContainer
{
PyObject_HEAD
void *d;
};
} // extern "C"
// Conversion helper traits for container values (Keep it out of namespace as
// otherwise clashes occur).
template <class Value>
struct ShibokenContainerValueConverter
{
static bool checkValue(PyObject *pyArg);
static PyObject *convertValueToPython(Value v);
static std::optional<Value> convertValueToCpp(PyObject pyArg);
};
// SFINAE test for the presence of reserve() in a sequence container (std::vector/QList)
template <typename T>
class ShibokenContainerHasReserve
{
private:
using YesType = char[1];
using NoType = char[2];
template <typename C> static YesType& test( decltype(&C::reserve) ) ;
template <typename C> static NoType& test(...);
public:
enum { value = sizeof(test<T>(nullptr)) == sizeof(YesType) };
};
// PYSIDE-3259 Handling of the std::vector<bool> optimization for providing
// a pointer for the SbkConverter. Use const-ref for the standard case to
// avoid copies and instantiate a bool in case of std::vector<bool>.
template <typename T>
struct ShibokenContainerStdVectorValueType
{
using Type = const T &;
};
template <>
struct ShibokenContainerStdVectorValueType<bool>
{
using Type = bool;
};
class ShibokenSequenceContainerPrivateBase
{
public:
static constexpr const char *msgModifyConstContainer =
"Attempt to modify a constant container.";
protected:
LIBSHIBOKEN_API static ShibokenContainer *allocContainer(PyTypeObject *subtype);
LIBSHIBOKEN_API static void freeSelf(PyObject *pySelf);
};
// Helper for sequence type containers
template <class SequenceContainer>
class ShibokenSequenceContainerPrivate : public ShibokenSequenceContainerPrivateBase
{
public:
using value_type = typename SequenceContainer::value_type;
using OptionalValue = typename std::optional<value_type>;
SequenceContainer *m_list{};
bool m_ownsList = false;
bool m_const = false;
static PyObject *tpNew(PyTypeObject *subtype, PyObject * /* args */, PyObject * /* kwds */)
{
auto *me = allocContainer(subtype);
auto *d = new ShibokenSequenceContainerPrivate;
d->m_list = new SequenceContainer;
d->m_ownsList = true;
me->d = d;
return reinterpret_cast<PyObject *>(me);
}
static PyObject *tpNewInvalid(PyTypeObject * /* subtype */, PyObject * /* args */, PyObject * /* kwds */)
{
return PyErr_Format(PyExc_NotImplementedError,
"Opaque containers of type '%s' cannot be instantiated.",
typeid(SequenceContainer).name());
}
static int tpInit(PyObject * /* self */, PyObject * /* args */, PyObject * /* kwds */)
{
return 0;
}
static void tpFree(void *self)
{
auto *pySelf = reinterpret_cast<PyObject *>(self);
auto *d = get(pySelf);
if (d->m_ownsList)
delete d->m_list;
delete d;
freeSelf(pySelf);
}
static Py_ssize_t sqLen(PyObject *self)
{
return get(self)->m_list->size();
}
static PyObject *sqGetItem(PyObject *self, Py_ssize_t i)
{
auto *d = get(self);
if (i < 0 || i >= Py_ssize_t(d->m_list->size()))
return PyErr_Format(PyExc_IndexError, "index out of bounds");
auto it = std::cbegin(*d->m_list);
std::advance(it, i);
return ShibokenContainerValueConverter<value_type>::convertValueToPython(*it);
}
static int sqSetItem(PyObject *self, Py_ssize_t i, PyObject *pyArg)
{
auto *d = get(self);
if (i < 0 || i >= Py_ssize_t(d->m_list->size())) {
PyErr_SetString(PyExc_IndexError, "index out of bounds");
return -1;
}
auto it = std::begin(*d->m_list);
std::advance(it, i);
OptionalValue value = ShibokenContainerValueConverter<value_type>::convertValueToCpp(pyArg);
if (!value.has_value())
return -1;
*it = value.value();
return 0;
}
static PyObject *push_back(PyObject *self, PyObject *pyArg)
{
auto *d = get(self);
if (!ShibokenContainerValueConverter<value_type>::checkValue(pyArg))
return PyErr_Format(PyExc_TypeError, "wrong type passed to append.");
if (d->m_const)
return PyErr_Format(PyExc_TypeError, msgModifyConstContainer);
OptionalValue value = ShibokenContainerValueConverter<value_type>::convertValueToCpp(pyArg);
if (!value.has_value())
return nullptr;
d->m_list->push_back(value.value());
Py_RETURN_NONE;
}
static PyObject *push_front(PyObject *self, PyObject *pyArg)
{
auto *d = get(self);
if (!ShibokenContainerValueConverter<value_type>::checkValue(pyArg))
return PyErr_Format(PyExc_TypeError, "wrong type passed to append.");
if (d->m_const)
return PyErr_Format(PyExc_TypeError, msgModifyConstContainer);
OptionalValue value = ShibokenContainerValueConverter<value_type>::convertValueToCpp(pyArg);
if (!value.has_value())
return nullptr;
d->m_list->push_front(value.value());
Py_RETURN_NONE;
}
static PyObject *clear(PyObject *self)
{
auto *d = get(self);
if (d->m_const)
return PyErr_Format(PyExc_TypeError, msgModifyConstContainer);
d->m_list->clear();
Py_RETURN_NONE;
}
static PyObject *pop_back(PyObject *self)
{
auto *d = get(self);
if (d->m_const)
return PyErr_Format(PyExc_TypeError, msgModifyConstContainer);
d->m_list->pop_back();
Py_RETURN_NONE;
}
static PyObject *pop_front(PyObject *self)
{
auto *d = get(self);
if (d->m_const)
return PyErr_Format(PyExc_TypeError, msgModifyConstContainer);
d->m_list->pop_front();
Py_RETURN_NONE;
}
// Support for containers with reserve/capacity
static PyObject *reserve(PyObject *self, PyObject *pyArg)
{
auto *d = get(self);
if (PyLong_Check(pyArg) == 0)
return PyErr_Format(PyExc_TypeError, "wrong type passed to reserve().");
if (d->m_const)
return PyErr_Format(PyExc_TypeError, msgModifyConstContainer);
if constexpr (ShibokenContainerHasReserve<SequenceContainer>::value) {
const Py_ssize_t size = PyLong_AsSsize_t(pyArg);
d->m_list->reserve(size);
} else {
return PyErr_Format(PyExc_TypeError, "Container does not support reserve().");
}
Py_RETURN_NONE;
}
static PyObject *capacity(PyObject *self)
{
Py_ssize_t result = -1;
if constexpr (ShibokenContainerHasReserve<SequenceContainer>::value) {
const auto *d = get(self);
result = d->m_list->capacity();
}
return PyLong_FromSsize_t(result);
}
static PyObject *data(PyObject *self)
{
PyObject *result = nullptr;
if constexpr (ShibokenContainerHasReserve<SequenceContainer>::value) {
const auto *d = get(self);
auto *data = d->m_list->data();
const Py_ssize_t size = sizeof(value_type) * d->m_list->size();
result = Shiboken::Buffer::newObject(data, size, Shiboken::Buffer::ReadWrite);
} else {
PyErr_SetString(PyExc_TypeError, "Container does not support data().");
}
return result;
}
static PyObject *constData(PyObject *self)
{
PyObject *result = nullptr;
if constexpr (ShibokenContainerHasReserve<SequenceContainer>::value) {
const auto *d = get(self);
const auto *data = std::as_const(d->m_list)->data();
const Py_ssize_t size = sizeof(value_type) * d->m_list->size();
result = Shiboken::Buffer::newObject(data, size);
} else {
PyErr_SetString(PyExc_TypeError, "Container does not support constData().");
}
return result;
}
static ShibokenSequenceContainerPrivate *get(PyObject *self)
{
auto *data = reinterpret_cast<ShibokenContainer *>(self);
return reinterpret_cast<ShibokenSequenceContainerPrivate *>(data->d);
}
};
namespace Shiboken
{
LIBSHIBOKEN_API bool isOpaqueContainer(PyObject *o);
}
#endif // SBK_CONTAINER_H

View File

@@ -0,0 +1,440 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBK_CONVERTER_H
#define SBK_CONVERTER_H
#include "sbkpython.h"
#include "sbkmodule.h"
#include "shibokenmacros.h"
#include "sbkenum.h"
#include "basewrapper_p.h"
#include <limits>
#include <string>
struct SbkObject;
/**
* This is a convenience macro identical to Python's PyObject_TypeCheck,
* except that the arguments have swapped places, for the great convenience
* of generator.
*/
#define SbkObject_TypeCheck(tp, ob) \
(Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp)))
extern "C"
{
/**
* SbkConverter is used to perform type conversions from C++
* to Python and vice-versa;.and it is also used for type checking.
* SbkConverter is a private structure that must be accessed
* using the functions provided by the converter API.
*/
struct SbkConverter;
struct SbkArrayConverter;
/**
* Given a void pointer to a C++ object, this function must return
* the proper Python object. It may be either an existing wrapper
* for the C++ object, or a newly create one. Or even the Python
* equivalent of the C++ value passed in the argument.
*
* C++ -> Python
*/
using CppToPythonFunc = PyObject *(*)(const void *);
/** Same as CppToPythonFunc, but additionally receives the 'PyTypeObject *'.
* This is handy for some converters, namely enumeration converters or
* dynamic user-defined converters that invoke the type object. */
using CppToPythonWithTypeFunc = PyObject *(*)(PyTypeObject *, const void *);
/**
* This function converts a Python object to a C++ value, it may be
* a pointer, value, class, container or primitive type, passed via
* a void pointer, that will be cast properly inside the function.
* This function is usually returned by an IsConvertibleToCppFunc
* function, or obtained knowing the type of the Python object input,
* thus it will not check the Python object type, and will expect
* the void pointer to be pointing to a proper variable.
*
* Python -> C++
*/
using PythonToCppFunc = void (*)(PyObject *,void *);
/**
* Checks if the Python object passed in the argument is convertible to a
* C++ type defined inside the function, it returns the converter function
* that will transform a Python argument into a C++ value.
* It returns NULL if the Python object is not convertible to the C++ type
* that the function represents.
*
* Python -> C++ ?
*/
using IsConvertibleToCppFunc = PythonToCppFunc (*)(PyObject *);
} // extern "C"
namespace Shiboken {
namespace Conversions {
class LIBSHIBOKEN_API SpecificConverter
{
public:
enum Type
{
InvalidConversion,
CopyConversion,
PointerConversion,
ReferenceConversion
};
explicit SpecificConverter(const char *typeName);
SbkConverter *converter() { return m_converter; }
operator SbkConverter *() const { return m_converter; }
bool isValid() { return m_type != InvalidConversion; }
operator bool() const { return m_type != InvalidConversion; }
Type conversionType() { return m_type; }
PyObject *toPython(const void *cppIn);
void toCpp(PyObject *pyIn, void *cppOut);
private:
SbkConverter *m_converter;
Type m_type;
};
/**
* Creates a converter for a wrapper type.
* \param type A Shiboken.ObjectType that will receive the new converter.
* \param toCppPointerConvFunc Function to retrieve the C++ pointer held by a Python wrapper.
* \param toCppPointerCheckFunc Check and return the retriever function of the C++ pointer held by a Python wrapper.
* \param pointerToPythonFunc Function to convert a C++ object to a Python \p type wrapper, keeping their identity.
* \param copyToPythonFunc Function to convert a C++ object to a Python \p type, copying the object.
* \returns The new converter referred by the wrapper \p type.
*/
LIBSHIBOKEN_API SbkConverter *createConverter(PyTypeObject *type,
PythonToCppFunc toCppPointerConvFunc,
IsConvertibleToCppFunc toCppPointerCheckFunc,
CppToPythonFunc pointerToPythonFunc,
CppToPythonFunc copyToPythonFunc = nullptr);
/**
* Creates a converter for a non wrapper type (primitive or container type).
* \param type Python type representing to the new converter.
* \param toPythonFunc Function to convert a C++ object to a Python \p type.
* \returns A new type converter.
*/
LIBSHIBOKEN_API SbkConverter *createConverter(PyTypeObject *type, CppToPythonFunc toPythonFunc);
LIBSHIBOKEN_API SbkConverter *createConverter(PyTypeObject *type, CppToPythonWithTypeFunc toPythonFunc);
LIBSHIBOKEN_API void deleteConverter(SbkConverter *converter);
/// Sets the Python object to C++ pointer conversion function.
LIBSHIBOKEN_API void setCppPointerToPythonFunction(SbkConverter *converter, CppToPythonFunc pointerToPythonFunc);
/// Sets the C++ pointer to Python object conversion functions.
LIBSHIBOKEN_API void setPythonToCppPointerFunctions(SbkConverter *converter,
PythonToCppFunc toCppPointerConvFunc,
IsConvertibleToCppFunc toCppPointerCheckFunc);
/**
* Adds a new conversion of a Python object to a C++ value.
* This is used in copy and implicit conversions.
*/
LIBSHIBOKEN_API void addPythonToCppValueConversion(SbkConverter *converter,
PythonToCppFunc pythonToCppFunc,
IsConvertibleToCppFunc isConvertibleToCppFunc);
LIBSHIBOKEN_API void prependPythonToCppValueConversion(SbkConverter *converter,
PythonToCppFunc pythonToCppFunc,
IsConvertibleToCppFunc isConvertibleToCppFunc);
LIBSHIBOKEN_API void addPythonToCppValueConversion(PyTypeObject *type,
PythonToCppFunc pythonToCppFunc,
IsConvertibleToCppFunc isConvertibleToCppFunc);
LIBSHIBOKEN_API void addPythonToCppValueConversion(Shiboken::Module::TypeInitStruct typeStruct,
PythonToCppFunc pythonToCppFunc,
IsConvertibleToCppFunc isConvertibleToCppFunc);
// C++ -> Python ---------------------------------------------------------------------------
/**
* Retrieves the Python wrapper object for the given \p cppIn C++ pointer object.
* This function is used only for Value and Object Types.
* Example usage:
* TYPE *var;
* PyObject *pyVar = pointerToPython(SBKTYPE, &var);
*/
LIBSHIBOKEN_API PyObject *pointerToPython(PyTypeObject *type, const void *cppIn);
LIBSHIBOKEN_API PyObject *pointerToPython(const SbkConverter *converter, const void *cppIn);
/**
* For the given \p cppIn C++ reference it returns the Python wrapper object,
* always for Object Types, and when they already exist for reference types;
* for when the latter doesn't have an existing wrapper type, the C++ object
* is copied to Python.
* Example usage:
* TYPE &var = SOMETHING;
* PyObject *pyVar = referenceToPython(SBKTYPE, &var);
*/
LIBSHIBOKEN_API PyObject *referenceToPython(PyTypeObject *type, const void *cppIn);
LIBSHIBOKEN_API PyObject *referenceToPython(const SbkConverter *converter, const void *cppIn);
/**
* Retrieves the Python wrapper object for the given C++ value pointed by \p cppIn.
* This function is used only for Value Types.
* Example usage:
* TYPE var;
* PyObject *pyVar = copyToPython(SBKTYPE, &var);
*/
LIBSHIBOKEN_API PyObject *copyToPython(PyTypeObject *type, const void *cppIn);
LIBSHIBOKEN_API PyObject *copyToPython(const SbkConverter *converter, const void *cppIn);
// Python -> C++ ---------------------------------------------------------------------------
struct PythonToCppConversion
{
enum Type {Invalid, Pointer, Value};
operator bool() const { return type != Invalid; }
void operator()(PyObject *po,void *cpp) const { function(po, cpp); }
bool isValue() const { return type == Value; }
PythonToCppFunc function = nullptr;
Type type = Invalid;
};
/**
* Returns a Python to C++ conversion function if the Python object is convertible to a C++ pointer.
* It returns NULL if the Python object is not convertible to \p type.
*/
LIBSHIBOKEN_API PythonToCppFunc isPythonToCppPointerConvertible(PyTypeObject *type, PyObject *pyIn);
LIBSHIBOKEN_API PythonToCppConversion pythonToCppPointerConversion(PyTypeObject *type, PyObject *pyIn);
LIBSHIBOKEN_API PythonToCppConversion pythonToCppPointerConversion(Module::TypeInitStruct typeStruct, PyObject *pyIn);
/**
* Returns a Python to C++ conversion function if the Python object is convertible to a C++ value.
* The resulting converter function will create a copy of the Python object in C++, or implicitly
* convert the object to the expected \p type.
* It returns NULL if the Python object is not convertible to \p type.
*/
LIBSHIBOKEN_API PythonToCppFunc isPythonToCppValueConvertible(PyTypeObject *type, PyObject *pyIn);
LIBSHIBOKEN_API PythonToCppConversion pythonToCppValueConversion(PyTypeObject *type, PyObject *pyIn);
/**
* Returns a Python to C++ conversion function if the Python object is convertible to a C++ reference.
* The resulting converter function will return the underlying C++ object held by the Python wrapper,
* or a new C++ value if it must be a implicit conversion.
* It returns NULL if the Python object is not convertible to \p type.
*/
LIBSHIBOKEN_API PythonToCppFunc isPythonToCppReferenceConvertible(PyTypeObject *type, PyObject *pyIn);
LIBSHIBOKEN_API PythonToCppConversion pythonToCppReferenceConversion(PyTypeObject *type, PyObject *pyIn);
/// This is the same as isPythonToCppValueConvertible function.
LIBSHIBOKEN_API PythonToCppFunc isPythonToCppConvertible(const SbkConverter *converter, PyObject *pyIn);
LIBSHIBOKEN_API PythonToCppConversion pythonToCppReferenceConversion(const SbkConverter *converter, PyObject *pyIn);
LIBSHIBOKEN_API PythonToCppConversion pythonToCppConversion(const SbkConverter *converter, PyObject *pyIn);
LIBSHIBOKEN_API PythonToCppFunc isPythonToCppConvertible(const SbkArrayConverter *converter,
int dim1, int dim2, PyObject *pyIn);
LIBSHIBOKEN_API PythonToCppConversion pythonToCppConversion(const SbkArrayConverter *converter,
int dim1, int dim2, PyObject *pyIn);
/**
* Returns the C++ pointer for the \p pyIn object cast to the type passed via \p desiredType.
* It differs from Shiboken::Object::cppPointer because it casts the pointer to a proper
* memory offset depending on the desired type.
*/
LIBSHIBOKEN_API void *cppPointer(PyTypeObject *desiredType, SbkObject *pyIn);
/// Converts a Python object \p pyIn to C++ and stores the result in the C++ pointer passed in \p cppOut.
LIBSHIBOKEN_API void pythonToCppPointer(PyTypeObject *type, PyObject *pyIn, void *cppOut);
LIBSHIBOKEN_API void pythonToCppPointer(const SbkConverter *converter, PyObject *pyIn, void *cppOut);
/// Converts a Python object \p pyIn to C++, and copies the result in the C++ variable passed in \p cppOut.
LIBSHIBOKEN_API void pythonToCppCopy(PyTypeObject *type, PyObject *pyIn, void *cppOut);
LIBSHIBOKEN_API void pythonToCppCopy(const SbkConverter *converter, PyObject *pyIn, void *cppOut);
/**
* Helper function returned by generated convertible checking functions
* that returns a C++ NULL when the input Python object is None.
*/
LIBSHIBOKEN_API void nonePythonToCppNullPtr(PyObject *, void *cppOut);
/**
* Returns true if the \p toCpp function passed is an implicit conversion of Python \p type.
* It is used when C++ expects a reference argument, so it may be the same object received
* from Python, or another created through implicit conversion.
*/
[[deprecated]] LIBSHIBOKEN_API bool isImplicitConversion(PyTypeObject *type, PythonToCppFunc toCpp);
/// Registers a converter with a type name that may be used to retrieve the converter.
/// Use for fully qualified names (main type). This will overwrite existing converters
/// of the same name.
LIBSHIBOKEN_API void registerConverterName(SbkConverter *converter, const char *typeName);
/// Registers a converter with a type name that may be used to retrieve the converter
/// unless there is already a converter for the name. Use for partially qualified names.
LIBSHIBOKEN_API void registerConverterAlias(SbkConverter *converter, const char *typeName);
/// Returns the converter for a given type name, or NULL if it wasn't registered before.
LIBSHIBOKEN_API SbkConverter *getConverter(const char *typeName);
/// Returns the converter for a primitive type.
LIBSHIBOKEN_API SbkConverter *primitiveTypeConverter(int index);
/// Returns true if a Python sequence is comprised of objects of the given \p type.
LIBSHIBOKEN_API bool checkSequenceTypes(PyTypeObject *type, PyObject *pyIn);
/// Returns true if a Python type is iterable and comprised of objects of the
/// given \p type.
LIBSHIBOKEN_API bool checkIterableTypes(PyTypeObject *type, PyObject *pyIn);
/// Returns true if a Python sequence is comprised of objects of a type convertible to the one represented by the given \p converter.
LIBSHIBOKEN_API bool convertibleSequenceTypes(const SbkConverter *converter, PyObject *pyIn);
/// Returns true if a Python sequence is comprised of objects of a type convertible to \p type.
LIBSHIBOKEN_API bool convertibleSequenceTypes(PyTypeObject *type, PyObject *pyIn);
/// Returns true if a Python type is iterable and comprised of objects of a
/// type convertible to the one represented by the given \p converter.
LIBSHIBOKEN_API bool convertibleIterableTypes(const SbkConverter *converter, PyObject *pyIn);
/// Returns true if a Python type is iterable and comprised of objects of a
/// type convertible to \p type.
LIBSHIBOKEN_API bool convertibleIterableTypes(PyTypeObject *type, PyObject *pyIn);
/// Returns true if a Python sequence can be converted to a C++ pair.
LIBSHIBOKEN_API bool checkPairTypes(PyTypeObject *firstType, PyTypeObject *secondType, PyObject *pyIn);
/// Returns true if a Python sequence can be converted to a C++ pair.
LIBSHIBOKEN_API bool convertiblePairTypes(const SbkConverter *firstConverter, bool firstCheckExact,
const SbkConverter *secondConverter, bool secondCheckExact,
PyObject *pyIn);
/// Returns true if a Python dictionary can be converted to a C++ hash or map.
LIBSHIBOKEN_API bool checkDictTypes(PyTypeObject *keyType, PyTypeObject *valueType, PyObject *pyIn);
/// Returns true if a Python dictionary can be converted to a C++ multi hash/map.
/// The Python dictionary is expected to contain lists of values
bool checkMultiDictTypes(PyTypeObject *keyType, PyTypeObject *valueType,
PyObject *pyIn);
/// Returns true if a Python dictionary can be converted to a C++ hash or map.
LIBSHIBOKEN_API bool convertibleDictTypes(const SbkConverter *keyConverter, bool keyCheckExact,
const SbkConverter *valueConverter, bool valueCheckExact,
PyObject *pyIn);
/// Returns true if a Python dictionary can be converted to a C++ multi hash/map.
/// The Python dictionary is expected to contain lists of values
LIBSHIBOKEN_API bool convertibleMultiDictTypes(const SbkConverter *keyConverter,
bool keyCheckExact,
const SbkConverter *valueConverter,
bool valueCheckExact,
PyObject *pyIn);
/// Returns the Python type object associated with the given \p converter.
LIBSHIBOKEN_API PyTypeObject *getPythonTypeObject(const SbkConverter *converter);
/// Returns the Python type object for the given \p typeName.
LIBSHIBOKEN_API PyTypeObject *getPythonTypeObject(const char *typeName);
/// Returns true if the Python type associated with the converter is a value type.
LIBSHIBOKEN_API bool pythonTypeIsValueType(const SbkConverter *converter);
/// Returns true if the Python type associated with the converter is an object type.
LIBSHIBOKEN_API bool pythonTypeIsObjectType(const SbkConverter *converter);
/// Returns true if the Python type associated with the converter is a wrapper type.
LIBSHIBOKEN_API bool pythonTypeIsWrapperType(const SbkConverter *converter);
enum : int {
SBK_PY_LONG_LONG_IDX = 0,
// Qt5: name collision in QtCore after QBool is replaced by bool
SBK_BOOL_IDX_1 = 1,
SBK_CHAR_IDX = 2,
SBK_CONSTCHARPTR_IDX = 3,
SBK_DOUBLE_IDX = 4,
SBK_FLOAT_IDX = 5,
SBK_INT_IDX = 6,
SBK_SIGNEDINT_IDX = 6,
SBK_LONG_IDX = 7,
SBK_SHORT_IDX = 8,
SBK_SIGNEDCHAR_IDX = 9,
SBK_STD_STRING_IDX = 10,
SBK_STD_WSTRING_IDX = 11,
SBK_UNSIGNEDPY_LONG_LONG_IDX = 12,
SBK_UNSIGNEDCHAR_IDX = 13,
SBK_UNSIGNEDINT_IDX = 14,
SBK_UNSIGNEDLONG_IDX = 15,
SBK_UNSIGNEDSHORT_IDX = 16,
SBK_VOIDPTR_IDX = 17,
SBK_NULLPTR_T_IDX = 18
};
template<typename T> SbkConverter *PrimitiveTypeConverter() { return nullptr; }
template<> inline SbkConverter *PrimitiveTypeConverter<PY_LONG_LONG>() { return primitiveTypeConverter(SBK_PY_LONG_LONG_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<bool>() { return primitiveTypeConverter(SBK_BOOL_IDX_1); }
template<> inline SbkConverter *PrimitiveTypeConverter<char>() { return primitiveTypeConverter(SBK_CHAR_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<const char *>() { return primitiveTypeConverter(SBK_CONSTCHARPTR_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<double>() { return primitiveTypeConverter(SBK_DOUBLE_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<float>() { return primitiveTypeConverter(SBK_FLOAT_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<int>() { return primitiveTypeConverter(SBK_INT_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<long>() { return primitiveTypeConverter(SBK_LONG_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<short>() { return primitiveTypeConverter(SBK_SHORT_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<signed char>() { return primitiveTypeConverter(SBK_SIGNEDCHAR_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<std::string>() { return primitiveTypeConverter(SBK_STD_STRING_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<std::wstring>() { return primitiveTypeConverter(SBK_STD_WSTRING_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<unsigned PY_LONG_LONG>() { return primitiveTypeConverter(SBK_UNSIGNEDPY_LONG_LONG_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<unsigned char>() { return primitiveTypeConverter(SBK_UNSIGNEDCHAR_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<unsigned int>() { return primitiveTypeConverter(SBK_UNSIGNEDINT_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<unsigned long>() { return primitiveTypeConverter(SBK_UNSIGNEDLONG_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<unsigned short>() { return primitiveTypeConverter(SBK_UNSIGNEDSHORT_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<void *>() { return primitiveTypeConverter(SBK_VOIDPTR_IDX); }
template<> inline SbkConverter *PrimitiveTypeConverter<std::nullptr_t>() { return primitiveTypeConverter(SBK_NULLPTR_T_IDX); }
} // namespace Shiboken::Conversions
/**
* This function template is used to get the PyTypeObject of a C++ type T.
* All implementations should be provided by template specializations generated by the generator when
* T isn't a C++ primitive type.
* \see SpecialCastFunction
*/
template<typename T> PyTypeObject *SbkType() { return nullptr; }
// Below are the template specializations for C++ primitive types.
template<> inline PyTypeObject *SbkType<PY_LONG_LONG>() { return &PyLong_Type; }
template<> inline PyTypeObject *SbkType<bool>() { return &PyBool_Type; }
template<> inline PyTypeObject *SbkType<char>() { return &PyLong_Type; }
template<> inline PyTypeObject *SbkType<double>() { return &PyFloat_Type; }
template<> inline PyTypeObject *SbkType<float>() { return &PyFloat_Type; }
template<> inline PyTypeObject *SbkType<int>() { return &PyLong_Type; }
template<> inline PyTypeObject *SbkType<long>() { return &PyLong_Type; }
template<> inline PyTypeObject *SbkType<short>() { return &PyLong_Type; }
template<> inline PyTypeObject *SbkType<signed char>() { return &PyLong_Type; }
template<> inline PyTypeObject *SbkType<unsigned PY_LONG_LONG>() { return &PyLong_Type; }
template<> inline PyTypeObject *SbkType<unsigned char>() { return &PyLong_Type; }
template<> inline PyTypeObject *SbkType<unsigned int>() { return &PyLong_Type; }
template<> inline PyTypeObject *SbkType<unsigned long>() { return &PyLong_Type; }
template<> inline PyTypeObject *SbkType<unsigned short>() { return &PyLong_Type; }
template<> inline PyTypeObject *SbkType<std::nullptr_t>() { return Py_TYPE(&_Py_NoneStruct); }
} // namespace Shiboken
#define SbkChar_Check(X) (PyNumber_Check(X) || Shiboken::String::checkChar(X))
struct PySideQFlagsType;
struct SbkQFlagsTypePrivate
{
SbkConverter *converter;
};
#endif // SBK_CONVERTER_H

View File

@@ -0,0 +1,22 @@
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKCPPSTRING_H
#define SBKCPPSTRING_H
#include "sbkpython.h"
#include "shibokenmacros.h"
#include <string>
#include <string_view>
namespace Shiboken::String
{
LIBSHIBOKEN_API PyObject *fromCppString(const std::string &value);
LIBSHIBOKEN_API PyObject *fromCppStringView(std::string_view value);
LIBSHIBOKEN_API PyObject *fromCppWString(const std::wstring &value);
LIBSHIBOKEN_API void toCppString(PyObject *str, std::string *value);
LIBSHIBOKEN_API void toCppWString(PyObject *str, std::wstring *value);
} // namespace Shiboken::String
#endif // SBKCPPSTRING_H

View File

@@ -0,0 +1,41 @@
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKCPPTONUMPY_H
#define SBKCPPTONUMPY_H
#include <sbkpython.h>
#include <shibokenmacros.h>
#include <cstdint>
namespace Shiboken::Numpy
{
/// Create a one-dimensional numpy array of type uint8/NPY_BYTE
/// \param size Size
/// \param data Data
/// \return PyArrayObject
LIBSHIBOKEN_API PyObject *createByteArray1(Py_ssize_t size, const uint8_t *data);
/// Create a one-dimensional numpy array of type double/NPY_DOUBLE
/// \param size Size
/// \param data Data
/// \return PyArrayObject
LIBSHIBOKEN_API PyObject *createDoubleArray1(Py_ssize_t size, const double *data);
/// Create a one-dimensional numpy array of type float/NPY_FLOAT
/// \param size Size
/// \param data Data
/// \return PyArrayObject
LIBSHIBOKEN_API PyObject *createFloatArray1(Py_ssize_t size, const float *data);
/// Create a one-dimensional numpy array of type int/NPY_INT
/// \param size Size
/// \param data Data
/// \return PyArrayObject
LIBSHIBOKEN_API PyObject *createIntArray1(Py_ssize_t size, const int *data);
} //namespace Shiboken::Numpy
#endif // SBKCPPTONUMPY_H

View File

@@ -0,0 +1,121 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKENUM_H
#define SBKENUM_H
#include "sbkpython.h"
#include "shibokenmacros.h"
extern "C"
{
LIBSHIBOKEN_API bool PyEnumMeta_Check(PyObject *ob);
/// exposed for the signature module
LIBSHIBOKEN_API void init_enum();
struct SbkConverter;
struct SbkEnumType;
struct SbkEnumTypePrivate
{
SbkConverter *converter;
SbkConverter *flagsConverter;
};
/// PYSIDE-1735: Pass on the Python enum/flag information.
LIBSHIBOKEN_API void initEnumFlagsDict(PyTypeObject *type);
/// PYSIDE-1735: Make sure that we can import the Python enum implementation.
LIBSHIBOKEN_API PyTypeObject *getPyEnumMeta();
/// PYSIDE-1735: Helper function supporting QEnum
LIBSHIBOKEN_API int enumIsFlag(PyObject *ob_enum);
}
namespace Shiboken::Enum {
enum : int {
ENOPT_OLD_ENUM = 0x00, // PySide 6.6: no longer supported
ENOPT_NEW_ENUM = 0x01,
ENOPT_INHERIT_INT = 0x02,
ENOPT_GLOBAL_SHORTCUT = 0x04,
ENOPT_SCOPED_SHORTCUT = 0x08,
ENOPT_NO_FAKESHORTCUT = 0x10,
ENOPT_NO_FAKERENAMES = 0x20,
ENOPT_NO_ZERODEFAULT = 0x40,
ENOPT_NO_MISSING = 0x80,
};
LIBSHIBOKEN_API extern int enumOption;
using EnumValueType = long long;
LIBSHIBOKEN_API bool check(PyObject *obj);
LIBSHIBOKEN_API bool checkType(PyTypeObject *pyTypeObj);
LIBSHIBOKEN_API PyObject *newItem(PyTypeObject *enumType, EnumValueType itemValue,
const char *itemName = nullptr);
LIBSHIBOKEN_API EnumValueType getValue(PyObject *enumItem);
LIBSHIBOKEN_API PyObject *getEnumItemFromValue(PyTypeObject *enumType,
EnumValueType itemValue);
/// Sets the enum/flag's type converter.
LIBSHIBOKEN_API void setTypeConverter(PyTypeObject *type, SbkConverter *converter,
SbkConverter *flagsConverter = nullptr);
/// Creating Python enums for different types.
LIBSHIBOKEN_API PyTypeObject *createPythonEnum(PyObject *module,
const char *fullName, const char *enumItemStrings[], const int64_t enumValues[]);
LIBSHIBOKEN_API PyTypeObject *createPythonEnum(PyObject *module,
const char *fullName, const char *enumItemStrings[], const uint64_t enumValues[]);
LIBSHIBOKEN_API PyTypeObject *createPythonEnum(PyObject *module,
const char *fullName, const char *enumItemStrings[], const int32_t enumValues[]);
LIBSHIBOKEN_API PyTypeObject *createPythonEnum(PyObject *module,
const char *fullName, const char *enumItemStrings[], const uint32_t enumValues[]);
LIBSHIBOKEN_API PyTypeObject *createPythonEnum(PyObject *module,
const char *fullName, const char *enumItemStrings[], const int16_t enumValues[]);
LIBSHIBOKEN_API PyTypeObject *createPythonEnum(PyObject *module,
const char *fullName, const char *enumItemStrings[], const uint16_t enumValues[]);
LIBSHIBOKEN_API PyTypeObject *createPythonEnum(PyObject *module,
const char *fullName, const char *enumItemStrings[], const int8_t enumValues[]);
LIBSHIBOKEN_API PyTypeObject *createPythonEnum(PyObject *module,
const char *fullName, const char *enumItemStrings[], const uint8_t enumValues[]);
/// This template removes duplication by inlining necessary type casts.
template <typename IntT>
inline PyTypeObject *createPythonEnum(PyTypeObject *scope,
const char *fullName, const char *enumItemStrings[], const IntT enumValues[])
{
auto *obScope = reinterpret_cast<PyObject *>(scope);
return createPythonEnum(obScope, fullName, enumItemStrings, enumValues);
}
/**
* @brief Creates a Python enum type from a set of provided key/values pairs
*
* @param fullName The full name (including module and package depth) to be used for the newly
* created enum type.
* @param pyEnumItems The key/value pairs to be used for the enum.
* @param enumTypeName The name of the enum type to be used (i.e., "PyIntEnum", "PyFlag", etc)
* from Python's enum module.
* @param callDict The dictionary to be used for the call, allowing for additional keyword
* arguments to be passed, such as "boundary=KEEP".
*/
LIBSHIBOKEN_API PyTypeObject *createPythonEnum(const char *fullName,
PyObject *pyEnumItems,
const char *enumTypeName = "Enum",
PyObject *callDict = nullptr);
} // namespace Shiboken::Enum
#endif // SKB_PYENUM_H

View File

@@ -0,0 +1,110 @@
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKERRORS_H
#define SBKERRORS_H
#include "sbkpython.h"
#include "shibokenmacros.h"
#include <memory>
/// Craving for C++20 and std::source_location::current()
#if defined(_MSC_VER)
# define SBK_FUNC_INFO __FUNCSIG__
#elif defined(__GNUC__)
# define SBK_FUNC_INFO __PRETTY_FUNCTION__
#else
# define SBK_FUNC_INFO __FUNCTION__
#endif
namespace Shiboken
{
struct LIBSHIBOKEN_API PythonContextMarker
{
public:
PythonContextMarker(const PythonContextMarker &) = delete;
PythonContextMarker(PythonContextMarker &&) = delete;
PythonContextMarker &operator=(const PythonContextMarker &) = delete;
PythonContextMarker &operator=(PythonContextMarker &&) = delete;
explicit PythonContextMarker();
~PythonContextMarker();
void setBlocking();
};
namespace Errors
{
struct ErrorStore;
/// Temporarily stash an error set in Python
class Stash
{
public:
Stash(const Stash &) = delete;
Stash &operator=(const Stash &) = delete;
Stash(Stash &&) = delete;
Stash &operator=(Stash &&) = delete;
LIBSHIBOKEN_API Stash();
LIBSHIBOKEN_API ~Stash();
LIBSHIBOKEN_API operator bool() const { return getException() != nullptr; }
[[nodiscard]] LIBSHIBOKEN_API PyObject *getException() const;
/// Restore the stored error
LIBSHIBOKEN_API void restore();
/// Discard the stored error
LIBSHIBOKEN_API void release();
private:
std::unique_ptr<ErrorStore> m_store;
};
LIBSHIBOKEN_API void setIndexOutOfBounds(Py_ssize_t value, Py_ssize_t minValue,
Py_ssize_t maxValue);
LIBSHIBOKEN_API void setInstantiateAbstractClass(const char *name);
LIBSHIBOKEN_API void setInstantiateAbstractClassDisabledWrapper(const char *name);
LIBSHIBOKEN_API void setInstantiateNamespace(const char *name);
LIBSHIBOKEN_API void setInstantiateNonConstructible(const char *name);
LIBSHIBOKEN_API void setInvalidTypeDeletion(const char *name);
LIBSHIBOKEN_API void setOperatorNotImplemented();
LIBSHIBOKEN_API void setPureVirtualMethodError(const char *name);
LIBSHIBOKEN_API void setPrivateMethod(const char *name);
LIBSHIBOKEN_API void setReverseOperatorNotImplemented();
LIBSHIBOKEN_API void setSequenceTypeError(const char *expectedType);
LIBSHIBOKEN_API void setSetterTypeError(const char *name, const char *expectedType);
LIBSHIBOKEN_API void setWrongContainerType();
/// Report an error ASAP: Instead of printing, store for later re-raise.
/// This replaces `PyErr_Print`, which cannot report errors as exception.
/// To be used in contexts where raising errors is impossible.
LIBSHIBOKEN_API void storeErrorOrPrint();
/// Call storeErrorOrPrint() and print the context to report
/// errors when calling Python overrides of virtual functions.
LIBSHIBOKEN_API void storePythonOverrideErrorOrPrint(const char *className, const char *funcName);
/// Handle an error as in PyErr_Occurred(), but also check for errors which
/// were captured by `storeErrorOrPrint`.
/// To be used in normal error checks.
LIBSHIBOKEN_API PyObject *occurred();
} // namespace Errors
namespace Warnings
{
/// Warn about invalid return value of overwritten virtual
LIBSHIBOKEN_API void warnInvalidReturnValue(const char *className, const char *functionName,
const char *expectedType, const char *actualType);
LIBSHIBOKEN_API void warnDeprecated(const char *functionName);
LIBSHIBOKEN_API void warnDeprecated(const char *className, const char *functionName);
LIBSHIBOKEN_API void warnDeprecatedEnum(const char *enumName);
LIBSHIBOKEN_API void warnDeprecatedEnumValue(const char *enumName, const char *valueName);
} // namespace Warnings
} // namespace Shiboken
#endif // SBKERRORS_H

View File

@@ -0,0 +1,18 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKFEATURE_BASE_H
#define SBKFEATURE_BASE_H
extern "C"
{
LIBSHIBOKEN_API int currentSelectId(PyTypeObject *type);
LIBSHIBOKEN_API PyObject *mangled_type_getattro(PyTypeObject *type, PyObject *name);
LIBSHIBOKEN_API PyObject *Sbk_TypeGet___dict__(PyTypeObject *type, void *context);
LIBSHIBOKEN_API PyObject *SbkObject_GenericGetAttr(PyObject *obj, PyObject *name);
LIBSHIBOKEN_API int SbkObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value);
} // extern "C"
#endif // SBKFEATURE_BASE_H

View File

@@ -0,0 +1,101 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBK_MODULE_H
#define SBK_MODULE_H
#include "sbkpython.h"
#include "shibokenmacros.h"
extern "C"
{
struct SbkConverter;
}
namespace Shiboken::Module {
struct TypeInitStruct
{
PyTypeObject *type;
const char *fullName;
};
/// PYSIDE-2404: Replacing the arguments in cpythonTypeNameExt by a function.
LIBSHIBOKEN_API PyTypeObject *get(TypeInitStruct &typeStruct);
/// PYSIDE-2404: Make sure that mentioned classes really exist.
LIBSHIBOKEN_API void loadLazyClassesWithName(const char *name);
/// PYSIDE-2404: incarnate all classes for star imports.
LIBSHIBOKEN_API void resolveLazyClasses(PyObject *module);
/**
* Imports and returns the module named \p moduleName, or a NULL pointer in case of failure.
* If the module is already imported, it increments its reference count before returning it.
* \returns the module specified in \p moduleName or NULL if an error occurs.
*/
LIBSHIBOKEN_API PyObject *import(const char *moduleName);
/**
* Creates a new Python module named \p moduleName using the information passed in \p moduleData
* and calls exec() on it.
* \returns a newly created module.
*/
[[deprecated]] LIBSHIBOKEN_API PyObject *create(const char *moduleName, PyModuleDef *moduleData);
/// Creates a new Python module named \p moduleName using the information passed in \p moduleData.
/// exec() is not called (Support for Nuitka).
/// \returns a newly created module.
LIBSHIBOKEN_API PyObject *createOnly(const char *moduleName, PyModuleDef *moduleData);
/// Executes a module (multi-phase initialization helper)
LIBSHIBOKEN_API void exec(PyObject *module);
using TypeCreationFunction = PyTypeObject *(*)(PyObject *module);
/// Adds a type creation function to the module.
LIBSHIBOKEN_API void AddTypeCreationFunction(PyObject *module,
const char *name,
TypeCreationFunction func);
LIBSHIBOKEN_API void AddTypeCreationFunction(PyObject *module,
const char *enclosingName,
TypeCreationFunction func,
const char *subTypeNamePath);
/**
* Registers the list of types created by \p module.
* \param module Module where the types were created.
* \param types Array of PyTypeObject *objects representing the types created on \p module.
*/
LIBSHIBOKEN_API void registerTypes(PyObject *module, TypeInitStruct *types);
/**
* Retrieves the array of types.
* \param module Module where the types were created.
* \returns A pointer to the PyTypeObject *array of types.
*/
LIBSHIBOKEN_API TypeInitStruct *getTypes(PyObject *module);
/**
* Registers the list of converters created by \p module for non-wrapper types.
* \param module Module where the converters were created.
* \param converters Array of SbkConverter *objects representing the converters created on \p module.
*/
LIBSHIBOKEN_API void registerTypeConverters(PyObject *module, SbkConverter **converters);
/**
* Retrieves the array of converters.
* \param module Module where the converters were created.
* \returns A pointer to the SbkConverter *array of converters.
*/
LIBSHIBOKEN_API SbkConverter **getTypeConverters(PyObject *module);
/**
* Replace the dictionary of a module. This allows to use `__missing__`.
*/
LIBSHIBOKEN_API bool replaceModuleDict(PyObject *module, PyObject *modClass, PyObject *dict);
} // namespace Shiboken::Module
#endif // SBK_MODULE_H

View File

@@ -0,0 +1,16 @@
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBK_MODULE_P_H
#define SBK_MODULE_P_H
#include <string>
namespace Shiboken::Module {
/// PYSIDE-2404: Make sure that mentioned classes really exist.
void loadLazyClassesWithNameStd(const std::string &name);
} // namespace Shiboken::Module
#endif // SBK_MODULE_H

View File

@@ -0,0 +1,30 @@
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKNUMPYCHECK_H
#define SBKNUMPYCHECK_H
#include <sbkpython.h>
#include <shibokenmacros.h>
// This header provides a PyArray_Check() definition that can be used to avoid
// having to include the numpy headers. When using numpy headers, make sure
// to include this header after them to skip the definition. Also remember
// that import_array() must then be called to initialize numpy.
namespace Shiboken::Numpy
{
/// Check whether the object is a PyArrayObject
/// \param pyIn object
/// \return Whether it is a PyArrayObject
LIBSHIBOKEN_API bool check(PyObject *pyIn);
} //namespace Shiboken::Numpy
#ifndef PyArray_Check
# define PyArray_Check(op) Shiboken::Numpy::check(op)
#endif
#endif // SBKNUMPYCHECK_H

View File

@@ -0,0 +1,47 @@
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKNUMPYVIEW_H
#define SBKNUMPYVIEW_H
#include <sbkpython.h>
#include <shibokenmacros.h>
#include <iosfwd>
namespace Shiboken::Numpy
{
/// Check whether the object is a PyArrayObject
/// \param pyIn object
/// \return Whether it is a PyArrayObject
LIBSHIBOKEN_API bool check(PyObject *pyIn);
/// A simple view of an up to 2 dimensional, C-contiguous array of a standard
/// type. It can be passed to compilation units that do not include the
/// numpy headers.
struct LIBSHIBOKEN_API View
{
enum Type { Int, Unsigned, Float, Double, Int16, Unsigned16, Int64, Unsigned64 };
static View fromPyObject(PyObject *pyIn);
operator bool() const { return ndim > 0; }
/// Return whether rhs is of the same type and dimensionality
bool sameLayout(const View &rhs) const;
/// Return whether rhs is of the same type dimensionality and size
bool sameSize(const View &rhs) const;
int ndim = 0;
Py_ssize_t dimensions[2];
Py_ssize_t stride[2];
void *data = nullptr;
Type type = Int;
};
LIBSHIBOKEN_API std::ostream &operator<<(std::ostream &, const View &v);
} //namespace Shiboken::Numpy
#endif // SBKNUMPYVIEW_H

View File

@@ -0,0 +1,11 @@
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKPEP_H
#define SBKPEP_H
#include "sbkversion.h"
#include "sbkpython.h"
#include "pep384impl.h"
#endif // SBKPEP_H

View File

@@ -0,0 +1,32 @@
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKPEPBUFFER_H
#define SBKPEPBUFFER_H
#include "bufferprocs_py37.h"
// FIXME: Move back to sbktypefactory.h once Py_LIMITED_API >= 3.11
extern "C"
{
LIBSHIBOKEN_API PyTypeObject *SbkType_FromSpec_BMDWB(PyType_Spec *spec,
PyObject *bases,
PyTypeObject *meta,
int dictoffset,
int weaklistoffset,
PyBufferProcs *bufferprocs);
} // extern "C"
// FIXME: Move back to helper.h once Py_LIMITED_API >= 3.11
namespace Shiboken
{
struct LIBSHIBOKEN_API debugPyBuffer
{
explicit debugPyBuffer(const Py_buffer &b);
const Py_buffer &m_buffer;
};
} // namespace Shiboken
#endif // SBKBUFFER_H

View File

@@ -0,0 +1,41 @@
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKPYTHON_H
#define SBKPYTHON_H
// PYSIDE-2701: This definition is needed for all Python formats with "#".
#define PY_SSIZE_T_CLEAN
// Qt's "slots" macro collides with the "slots" member variables
// used in some Python structs. For compilers that support push_macro,
// temporarily undefine it.
#if defined(slots) && (defined(__GNUC__) || defined(_MSC_VER) || defined(__clang__))
# pragma push_macro("slots")
# undef slots
extern "C" {
# include <Python.h>
}
# include <structmember.h>
# pragma pop_macro("slots")
#else
extern "C" {
# include <Python.h>
}
# include <structmember.h>
#endif
// In Python 3, Py_TPFLAGS_DEFAULT contains Py_TPFLAGS_HAVE_VERSION_TAG,
// which will trigger the attribute cache, which is not intended in Qt for Python.
// Use a customized Py_TPFLAGS_DEFAULT by defining Py_TPFLAGS_HAVE_VERSION_TAG = 0.
#undef Py_TPFLAGS_HAVE_VERSION_TAG
#define Py_TPFLAGS_HAVE_VERSION_TAG (0)
using SbkObjectType [[deprecated]] = PyTypeObject; // FIXME PYSIDE 7 remove
#endif

View File

@@ -0,0 +1,18 @@
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBK_SBKSMARTPOINTER_H
#define SBK_SBKSMARTPOINTER_H
#include "sbkpython.h"
#include "shibokenmacros.h"
namespace Shiboken::SmartPointer
{
LIBSHIBOKEN_API PyObject *repr(PyObject *pointer, PyObject *pointee);
LIBSHIBOKEN_API PyObject *dir(PyObject *pointer, PyObject *pointee);
} // namespace Shiboken::SmartPointer
#endif // SBK_SBKSMARTPOINTER_H

View File

@@ -0,0 +1,61 @@
// Copyright (C) 2019 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKSTATICSTRINGS_H
#define SBKSTATICSTRINGS_H
#include "sbkpython.h"
#include "shibokenmacros.h"
namespace Shiboken
{
// Some often-used strings
namespace PyName
{
LIBSHIBOKEN_API PyObject *co_name();
LIBSHIBOKEN_API PyObject *dumps();
LIBSHIBOKEN_API PyObject *fget();
LIBSHIBOKEN_API PyObject *fset();
LIBSHIBOKEN_API PyObject *f_code();
LIBSHIBOKEN_API PyObject *f_lineno();
LIBSHIBOKEN_API PyObject *im_func();
LIBSHIBOKEN_API PyObject *im_self();
LIBSHIBOKEN_API PyObject *loads();
LIBSHIBOKEN_API PyObject *multi();
LIBSHIBOKEN_API PyObject *name();
LIBSHIBOKEN_API PyObject *orig_dict();
LIBSHIBOKEN_API PyObject *result();
LIBSHIBOKEN_API PyObject *select_id();
LIBSHIBOKEN_API PyObject *value();
LIBSHIBOKEN_API PyObject *values();
LIBSHIBOKEN_API PyObject *qtStaticMetaObject();
} // namespace PyName
namespace PyMagicName
{
LIBSHIBOKEN_API PyObject *class_();
LIBSHIBOKEN_API PyObject *dict();
LIBSHIBOKEN_API PyObject *doc();
LIBSHIBOKEN_API PyObject *ecf();
LIBSHIBOKEN_API PyObject *file();
LIBSHIBOKEN_API PyObject *func();
LIBSHIBOKEN_API PyObject *get();
LIBSHIBOKEN_API PyObject *members();
LIBSHIBOKEN_API PyObject *module();
LIBSHIBOKEN_API PyObject *name();
LIBSHIBOKEN_API PyObject *property_methods();
LIBSHIBOKEN_API PyObject *qualname();
LIBSHIBOKEN_API PyObject *self();
LIBSHIBOKEN_API PyObject *opaque_container();
LIBSHIBOKEN_API PyObject *code();
LIBSHIBOKEN_API PyObject *rlshift();
LIBSHIBOKEN_API PyObject *rrshift();
} // namespace PyMagicName
namespace Messages
{
LIBSHIBOKEN_API PyObject *unknownException();
} // Messages
} // namespace Shiboken
#endif // SBKSTATICSTRINGS_H

View File

@@ -0,0 +1,36 @@
// Copyright (C) 2019 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKSTRING_H
#define SBKSTRING_H
#include "sbkpython.h"
#include "shibokenmacros.h"
namespace Shiboken::String
{
LIBSHIBOKEN_API bool check(PyObject *obj);
LIBSHIBOKEN_API bool checkIterable(PyObject *obj);
/// Check for iterable function arguments (excluding enumerations)
LIBSHIBOKEN_API bool checkIterableArgument(PyObject *obj);
LIBSHIBOKEN_API bool checkPath(PyObject *path);
LIBSHIBOKEN_API bool checkType(PyTypeObject *obj);
LIBSHIBOKEN_API bool checkChar(PyObject *obj);
LIBSHIBOKEN_API bool isConvertible(PyObject *obj);
LIBSHIBOKEN_API PyObject *fromCString(const char *value);
LIBSHIBOKEN_API PyObject *fromCString(const char *value, int len);
LIBSHIBOKEN_API const char *toCString(PyObject *str);
LIBSHIBOKEN_API const char *toCString(PyObject *str, Py_ssize_t *len);
LIBSHIBOKEN_API bool concat(PyObject **val1, PyObject *val2);
LIBSHIBOKEN_API PyObject *fromFormat(const char *format, ...);
LIBSHIBOKEN_API PyObject *fromStringAndSize(const char *str, Py_ssize_t size);
LIBSHIBOKEN_API int compare(PyObject *val1, const char *val2);
LIBSHIBOKEN_API Py_ssize_t len(PyObject *str);
LIBSHIBOKEN_API PyObject *createStaticString(const char *str);
LIBSHIBOKEN_API PyObject *getSnakeCaseName(const char *name, bool lower);
LIBSHIBOKEN_API PyObject *getSnakeCaseName(PyObject *name, bool lower);
LIBSHIBOKEN_API PyObject *repr(PyObject *o);
} // namespace Shiboken::String
#endif

View File

@@ -0,0 +1,21 @@
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKTYPEFACTORY_H
#define SBKTYPEFACTORY_H
#include "sbkpepbuffer.h"
#include "shibokenmacros.h"
extern "C"
{
// PYSIDE-535: Encapsulation of PyType_FromSpec special-cased for PyPy
LIBSHIBOKEN_API PyTypeObject *SbkType_FromSpec(PyType_Spec *);
LIBSHIBOKEN_API PyTypeObject *SbkType_FromSpecWithMeta(PyType_Spec *, PyTypeObject *);
LIBSHIBOKEN_API PyTypeObject *SbkType_FromSpecWithBases(PyType_Spec *, PyObject *);
LIBSHIBOKEN_API PyTypeObject *SbkType_FromSpecBasesMeta(PyType_Spec *, PyObject *, PyTypeObject *);
} //extern "C"
#endif // SBKTYPEFACTORY_H

View File

@@ -0,0 +1,17 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKVERSION_H
#define SBKVERSION_H
#define SHIBOKEN_VERSION "6.10.2"
#define SHIBOKEN_MAJOR_VERSION 6
#define SHIBOKEN_MINOR_VERSION 10
#define SHIBOKEN_MICRO_VERSION 2
#define SHIBOKEN_RELEASE_LEVEL "final"
#define SHIBOKEN_SERIAL 0
#define PYTHON_VERSION_MAJOR 3
#define PYTHON_VERSION_MINOR 10
#define PYTHON_VERSION_PATCH 0
#endif

View File

@@ -0,0 +1,17 @@
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SBKWINDOWS_H
#define SBKWINDOWS_H
#ifdef _WIN32
# ifndef NOMINMAX
# define NOMINMAX
# endif
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
#endif
#endif // SBKWINDOWS_H

View File

@@ -0,0 +1,28 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SHIBOKEN_H
#define SHIBOKEN_H
#include "sbkpython.h"
#include "autodecref.h"
#include "basewrapper.h"
#include "bindingmanager.h"
#include "gilstate.h"
#include "threadstatesaver.h"
#include "helper.h"
#include "pyobjectholder.h"
#include "sbkarrayconverter.h"
#include "sbkbindingutils.h"
#include "sbkconverter.h"
#include "sbkenum.h"
#include "sbkerrors.h"
#include "sbkmodule.h"
#include "sbkstring.h"
#include "sbkstaticstrings.h"
#include "sbktypefactory.h"
#include "shibokenmacros.h"
#include "shibokenbuffer.h"
#include "signature.h"
#endif // SHIBOKEN_H

View File

@@ -0,0 +1,53 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SHIBOKEN_BUFFER_H
#define SHIBOKEN_BUFFER_H
#include "sbkpython.h"
#include "shibokenmacros.h"
namespace Shiboken::Buffer
{
enum Type {
ReadOnly,
WriteOnly,
ReadWrite
};
/**
* Creates a new Python buffer pointing to a contiguous memory block at
* \p memory of size \p size.
*/
LIBSHIBOKEN_API PyObject *newObject(void *memory, Py_ssize_t size, Type type);
/**
* Creates a new <b>read only</b> Python buffer pointing to a contiguous memory block at
* \p memory of size \p size.
*/
LIBSHIBOKEN_API PyObject *newObject(const void *memory, Py_ssize_t size);
/**
* Check if is ok to use \p pyObj as argument in all function under Shiboken::Buffer namespace.
*/
LIBSHIBOKEN_API bool checkType(PyObject *pyObj);
/**
* Returns a pointer to the memory pointed by the buffer \p pyObj, \p size is filled with the buffer
* size if not null.
*
* If the \p pyObj is a non-contiguous buffer a Python error is set.
*/
LIBSHIBOKEN_API void *getPointer(PyObject *pyObj, Py_ssize_t *size = nullptr);
/**
* Returns a copy of the buffer data which should be free'd.
*
* If the \p pyObj is a non-contiguous buffer a Python error is set.
* nullptr is returned for empty buffers.
*/
LIBSHIBOKEN_API void *copyData(PyObject *pyObj, Py_ssize_t *size = nullptr);
} // namespace Shiboken::Buffer
#endif

View File

@@ -0,0 +1,26 @@
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SHIBOKENMACROS_H
#define SHIBOKENMACROS_H
// LIBSHIBOKEN_API macro is used for the public API symbols.
#if defined _WIN32
# define LIBSHIBOKEN_EXPORT __declspec(dllexport)
# ifdef _MSC_VER
# define LIBSHIBOKEN_IMPORT __declspec(dllimport)
# else
# define LIBSHIBOKEN_IMPORT
# endif
#else
# define LIBSHIBOKEN_EXPORT __attribute__ ((visibility("default")))
# define LIBSHIBOKEN_IMPORT
#endif
#ifdef BUILD_LIBSHIBOKEN
# define LIBSHIBOKEN_API LIBSHIBOKEN_EXPORT
#else
# define LIBSHIBOKEN_API LIBSHIBOKEN_IMPORT
#endif
#endif // SHIBOKENMACROS_H

View File

@@ -0,0 +1,23 @@
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SIGNATURE_H
#define SIGNATURE_H
#include "shibokenmacros.h"
#include "sbkpython.h"
extern "C"
{
LIBSHIBOKEN_API int InitSignatureStrings(PyTypeObject *, const char *[]);
LIBSHIBOKEN_API int InitSignatureBytes(PyTypeObject *, const uint8_t[], size_t);
LIBSHIBOKEN_API int FinishSignatureInitialization(PyObject *, const char *[]);
LIBSHIBOKEN_API int FinishSignatureInitBytes(PyObject *, const uint8_t [], size_t);
LIBSHIBOKEN_API void SetError_Argument(PyObject *, const char *, PyObject *);
LIBSHIBOKEN_API PyObject *Sbk_TypeGet___doc__(PyObject *);
LIBSHIBOKEN_API PyObject *GetFeatureDict();
} // extern "C"
#endif // SIGNATURE_H

View File

@@ -0,0 +1,79 @@
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef SIGNATURE_IMPL_H
#define SIGNATURE_IMPL_H
#include "signature.h"
extern "C" {
// signature_globals.cpp
struct safe_globals_struc {
// init part 1: get arg_dict
PyObject *helper_module;
PyObject *arg_dict;
PyObject *map_dict;
PyObject *value_dict; // for writing signatures
PyObject *feature_dict; // registry for PySide.support.__feature__
// init part 2: run module
PyObject *pyside_type_init_func;
PyObject *create_signature_func;
PyObject *seterror_argument_func;
PyObject *make_helptext_func;
PyObject *finish_import_func;
PyObject *feature_import_func;
PyObject *feature_imported_func;
};
extern safe_globals_struc *pyside_globals;
extern PyMethodDef signature_methods[];
void init_shibokensupport_module(void);
// signature.cpp
PyObject *GetTypeKey(PyObject *ob);
PyObject *GetSignature_Function(PyObject *, PyObject *);
PyObject *GetSignature_TypeMod(PyObject *, PyObject *);
PyObject *GetSignature_Wrapper(PyObject *, PyObject *);
LIBSHIBOKEN_API PyObject *get_signature_intern(PyObject *ob, PyObject *modifier);
PyObject *PySide_BuildSignatureProps(PyObject *class_mod);
PyObject *GetClassOrModOf(PyObject *ob);
// signature_extend.cpp
PyObject *pyside_cf_get___signature__(PyObject *func, PyObject *modifier);
PyObject *pyside_sm_get___signature__(PyObject *sm, PyObject *modifier);
PyObject *pyside_md_get___signature__(PyObject *ob_md, PyObject *modifier);
PyObject *pyside_wd_get___signature__(PyObject *ob, PyObject *modifier);
PyObject *pyside_tp_get___signature__(PyObject *obtype_mod, PyObject *modifier);
int PySide_PatchTypes(void);
PyObject *pyside_tp_get___doc__(PyObject *tp);
// signature_helper.cpp
int add_more_getsets(PyTypeObject *type, PyGetSetDef *gsp, PyObject **doc_descr);
PyObject *name_key_to_func(PyObject *ob);
int insert_snake_case_variants(PyObject *dict);
PyObject *_get_class_of_cf(PyObject *ob_cf);
PyObject *_get_class_of_sm(PyObject *ob_sm);
PyObject *_get_class_of_descr(PyObject *ob);
PyObject *_address_to_stringlist(PyObject *numkey);
PyObject *_address_ptr_to_stringlist(const char **sig_strings);
int _build_func_to_type(PyObject *obtype);
int _finish_nested_classes(PyObject *dict);
#ifdef PYPY_VERSION
// PyPy has a special builtin method.
PyObject *GetSignature_Method(PyObject *, PyObject *);
PyObject *pyside_bm_get___signature__(PyObject *func, PyObject *modifier);
PyObject *_get_class_of_bm(PyObject *ob_cf);
#endif
} // extern "C"
#endif // SIGNATURE_IMPL_H

View File

@@ -0,0 +1,31 @@
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef THREADSTATESAVER_H
#define THREADSTATESAVER_H
#include "sbkpython.h"
#include <shibokenmacros.h>
namespace Shiboken
{
class LIBSHIBOKEN_API ThreadStateSaver
{
public:
ThreadStateSaver(const ThreadStateSaver &) = delete;
ThreadStateSaver(ThreadStateSaver &&) = delete;
ThreadStateSaver &operator=(const ThreadStateSaver &) = delete;
ThreadStateSaver &operator=(ThreadStateSaver &&) = delete;
ThreadStateSaver();
~ThreadStateSaver();
void save();
void restore();
private:
PyThreadState *m_threadState = nullptr;
};
} // namespace Shiboken
#endif // THREADSTATESAVER_H

View File

@@ -0,0 +1,33 @@
// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef VOIDPTR_H
#define VOIDPTR_H
#include "sbkpython.h"
#include "shibokenmacros.h"
#include "sbkconverter.h"
extern "C"
{
// Void pointer type declaration.
extern LIBSHIBOKEN_API PyTypeObject *SbkVoidPtr_TypeF(void);
} // extern "C"
namespace VoidPtr
{
void init();
SbkConverter *createConverter();
LIBSHIBOKEN_API void addVoidPtrToModule(PyObject *module);
LIBSHIBOKEN_API void setSize(PyObject *voidPtr, Py_ssize_t size);
LIBSHIBOKEN_API Py_ssize_t getSize(PyObject *voidPtr);
LIBSHIBOKEN_API bool isWritable(PyObject *voidPtr);
LIBSHIBOKEN_API void setWritable(PyObject *voidPtr, bool isWritable);
}
#endif // VOIDPTR_H

View File

@@ -0,0 +1,62 @@
# SHIBOKEN_BUILD_TYPE - Tells if Shiboken was compiled in Release or Debug mode.
# SHIBOKEN_PYTHON_INTERPRETER - Python interpreter (regular or debug) to be used with the bindings.
####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() #######
####### Any changes to this file will be overwritten by the next CMake run ####
####### The input file was Shiboken6Config-spec.cmake.in ########
get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE)
macro(set_and_check _var _file)
set(${_var} "${_file}")
if(NOT EXISTS "${_file}")
message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !")
endif()
endmacro()
macro(check_required_components _NAME)
foreach(comp ${${_NAME}_FIND_COMPONENTS})
if(NOT ${_NAME}_${comp}_FOUND)
if(${_NAME}_FIND_REQUIRED_${comp})
set(${_NAME}_FOUND FALSE)
endif()
endif()
endforeach()
endmacro()
####################################################################################
# This is the version of Python against which Shiboken was built. Not necessarily the version
# against which a downstream project is built (e.g. PySide6).
set(SHIBOKEN_PYTHON_VERSION_MAJOR "3")
set(SHIBOKEN_PYTHON_VERSION_MINOR "10")
set(SHIBOKEN_PYTHON_VERSION_PATCH "0")
set(SHIBOKEN_PYTHON_LIMITED_API "1")
# Import targets and call variable set up functions only when using an installed shiboken config
# file (so not during a regular shiboken build, or during a super project build).
if (NOT TARGET Shiboken6::libshiboken)
include("${CMAKE_CURRENT_LIST_DIR}/Shiboken6Targets.cmake")
include("${CMAKE_CURRENT_LIST_DIR}/ShibokenHelpers.cmake")
# Compute the python include and libraries path if needed (aka not part of super project build).
shiboken_find_required_python(3)
shiboken_check_if_built_and_target_python_are_compatible()
shiboken_check_if_limited_api()
shiboken_compute_python_includes(IS_CALLED_FROM_EXPORT)
shiboken_compute_python_libraries(IS_CALLED_FROM_EXPORT)
endif()
# Get the "python interpreter" dynamic global property as a variable instead. It brings it into
# scope for super project builds.
get_property(SHIBOKEN_PYTHON_INTERPRETER GLOBAL PROPERTY SHIBOKEN_PYTHON_INTERPRETER)
# Set static variables.
set(SHIBOKEN_PYTHON_EXTENSION_SUFFIX "")
set(SHIBOKEN_PYTHON_SHARED_LIBRARY_SUFFIX ".abi3")
set(SHIBOKEN_PYTHON_CONFIG_SUFFIX ".abi3")
set(SHIBOKEN_SO_VERSION "6.10")
set(SHIBOKEN_BUILD_TYPE "Release")
message(STATUS "libshiboken built for Release")

View File

@@ -0,0 +1,5 @@
if (NOT PYTHON_CONFIG_SUFFIX)
message(STATUS "Shiboken6Config: Using default python: .abi3")
SET(PYTHON_CONFIG_SUFFIX .abi3)
endif()
include("${CMAKE_CURRENT_LIST_DIR}/Shiboken6Config${PYTHON_CONFIG_SUFFIX}.cmake")

View File

@@ -0,0 +1,10 @@
set(PACKAGE_VERSION 6.10.2)
if("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}" )
set(PACKAGE_VERSION_COMPATIBLE FALSE)
else("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}" )
set(PACKAGE_VERSION_COMPATIBLE TRUE)
if( "${PACKAGE_FIND_VERSION}" STREQUAL "${PACKAGE_VERSION}")
set(PACKAGE_VERSION_EXACT TRUE)
endif( "${PACKAGE_FIND_VERSION}" STREQUAL "${PACKAGE_VERSION}")
endif("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}" )

View File

@@ -0,0 +1,19 @@
#----------------------------------------------------------------
# Generated CMake target import file for configuration "Release".
#----------------------------------------------------------------
# Commands may need to know the format version.
set(CMAKE_IMPORT_FILE_VERSION 1)
# Import target "Shiboken6::libshiboken" for configuration "Release"
set_property(TARGET Shiboken6::libshiboken APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(Shiboken6::libshiboken PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/shiboken6/shiboken6.abi3.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/shiboken6/shiboken6.abi3.dll"
)
list(APPEND _cmake_import_check_targets Shiboken6::libshiboken )
list(APPEND _cmake_import_check_files_for_Shiboken6::libshiboken "${_IMPORT_PREFIX}/shiboken6/shiboken6.abi3.lib" "${_IMPORT_PREFIX}/shiboken6/shiboken6.abi3.dll" )
# Commands beyond this point should not need to know the version.
set(CMAKE_IMPORT_FILE_VERSION)

View File

@@ -0,0 +1,108 @@
# Generated by CMake
if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.8)
message(FATAL_ERROR "CMake >= 2.8.0 required")
endif()
if(CMAKE_VERSION VERSION_LESS "2.8.3")
message(FATAL_ERROR "CMake >= 2.8.3 required")
endif()
cmake_policy(PUSH)
cmake_policy(VERSION 2.8.3...3.28)
#----------------------------------------------------------------
# Generated CMake target import file.
#----------------------------------------------------------------
# Commands may need to know the format version.
set(CMAKE_IMPORT_FILE_VERSION 1)
# Protect against multiple inclusion, which would fail when already imported targets are added once more.
set(_cmake_targets_defined "")
set(_cmake_targets_not_defined "")
set(_cmake_expected_targets "")
foreach(_cmake_expected_target IN ITEMS Shiboken6::libshiboken)
list(APPEND _cmake_expected_targets "${_cmake_expected_target}")
if(TARGET "${_cmake_expected_target}")
list(APPEND _cmake_targets_defined "${_cmake_expected_target}")
else()
list(APPEND _cmake_targets_not_defined "${_cmake_expected_target}")
endif()
endforeach()
unset(_cmake_expected_target)
if(_cmake_targets_defined STREQUAL _cmake_expected_targets)
unset(_cmake_targets_defined)
unset(_cmake_targets_not_defined)
unset(_cmake_expected_targets)
unset(CMAKE_IMPORT_FILE_VERSION)
cmake_policy(POP)
return()
endif()
if(NOT _cmake_targets_defined STREQUAL "")
string(REPLACE ";" ", " _cmake_targets_defined_text "${_cmake_targets_defined}")
string(REPLACE ";" ", " _cmake_targets_not_defined_text "${_cmake_targets_not_defined}")
message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_cmake_targets_defined_text}\nTargets not yet defined: ${_cmake_targets_not_defined_text}\n")
endif()
unset(_cmake_targets_defined)
unset(_cmake_targets_not_defined)
unset(_cmake_expected_targets)
# Compute the installation prefix relative to this file.
get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH)
get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
if(_IMPORT_PREFIX STREQUAL "/")
set(_IMPORT_PREFIX "")
endif()
# Create imported target Shiboken6::libshiboken
add_library(Shiboken6::libshiboken SHARED IMPORTED)
set_target_properties(Shiboken6::libshiboken PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "Py_LIMITED_API=0x03090000;NDEBUG"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/shiboken6/include"
)
# Load information for each installed configuration.
file(GLOB _cmake_config_files "${CMAKE_CURRENT_LIST_DIR}/Shiboken6Targets-*.cmake")
foreach(_cmake_config_file IN LISTS _cmake_config_files)
include("${_cmake_config_file}")
endforeach()
unset(_cmake_config_file)
unset(_cmake_config_files)
# Cleanup temporary variables.
set(_IMPORT_PREFIX)
# Loop over all imported files and verify that they actually exist
foreach(_cmake_target IN LISTS _cmake_import_check_targets)
if(CMAKE_VERSION VERSION_LESS "3.28"
OR NOT DEFINED _cmake_import_check_xcframework_for_${_cmake_target}
OR NOT IS_DIRECTORY "${_cmake_import_check_xcframework_for_${_cmake_target}}")
foreach(_cmake_file IN LISTS "_cmake_import_check_files_for_${_cmake_target}")
if(NOT EXISTS "${_cmake_file}")
message(FATAL_ERROR "The imported target \"${_cmake_target}\" references the file
\"${_cmake_file}\"
but this file does not exist. Possible reasons include:
* The file was deleted, renamed, or moved to another location.
* An install or uninstall procedure did not complete successfully.
* The installation package was faulty and contained
\"${CMAKE_CURRENT_LIST_FILE}\"
but not all the files it references.
")
endif()
endforeach()
endif()
unset(_cmake_file)
unset("_cmake_import_check_files_for_${_cmake_target}")
endforeach()
unset(_cmake_target)
unset(_cmake_import_check_targets)
# This file does not depend on other imported targets which have
# been exported from the same project but in a separate export set.
# Commands beyond this point should not need to know the version.
set(CMAKE_IMPORT_FILE_VERSION)
cmake_policy(POP)

View File

@@ -0,0 +1,905 @@
# Copyright (C) 2023 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause
include(CMakeParseArguments)
macro(set_limited_api)
if (WIN32 AND NOT EXISTS "${PYTHON_LIMITED_LIBRARIES}")
message(FATAL_ERROR "The Limited API was enabled, but ${PYTHON_LIMITED_LIBRARIES} was not found!")
endif()
message(STATUS "******************************************************")
message(STATUS "** Limited API enabled ${PYTHON_LIMITED_LIBRARIES}")
message(STATUS "******************************************************")
endmacro()
macro(set_debug_build)
set(SHIBOKEN_BUILD_TYPE "Debug")
if(NOT Python_LIBRARIES)
message(WARNING "Python debug shared library not found; \
assuming python was built with shared library support disabled.")
endif()
if(NOT PYTHON_WITH_DEBUG)
message(WARNING "Compiling shiboken6 with debug enabled, \
but the python executable was not compiled with debug support.")
else()
set(SBK_PKG_CONFIG_PY_DEBUG_DEFINITION " -DPy_DEBUG")
endif()
if (PYTHON_WITH_COUNT_ALLOCS)
set(SBK_PKG_CONFIG_PY_DEBUG_DEFINITION "${SBK_PKG_CONFIG_PY_DEBUG_DEFINITION} -DCOUNT_ALLOCS")
endif()
endmacro()
macro(setup_sanitize_address)
# Currently this does not check that the clang / gcc / MSVC version used supports Address
# sanitizer, so once again, use at your own risk.
if(MSVC)
add_compile_options("/fsanitize=address")
else()
add_compile_options("-fsanitize=address" "-g" "-fno-omit-frame-pointer")
endif()
# We need to add the sanitize address option to all linked executables / shared libraries
# so that proper sanitizer symbols are linked in.
#
# Note that when running tests, you may need to set an additional environment variable
# in set_tests_properties for shiboken6 / pyside tests, or exported in your shell. Address
# sanitizer will tell you what environment variable needs to be exported. For example:
# export DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Toolchains/
# ./XcodeDefault.xctoolchain/usr/lib/clang/8.1.0/lib/darwin/libclang_rt.asan_osx_dynamic.dylib
if(MSVC)
set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_STANDARD_LIBRARIES} /fsanitize=address")
else()
set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_STANDARD_LIBRARIES} -fsanitize=address")
endif()
endmacro()
macro(setup_sanitize_thread)
if(MSVC)
set(sanitize_thread_option "/fsanitize=thread")
else()
set(sanitize_thread_option "-fsanitize=thread")
endif()
add_compile_options("${sanitize_thread_option}")
set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_STANDARD_LIBRARIES} ${sanitize_thread_option}")
endmacro()
macro(set_cmake_cxx_flags)
if(MSVC)
# Qt5: this flag has changed from /Zc:wchar_t- in Qt4.X
set(CMAKE_CXX_FLAGS "/Zc:wchar_t /GR /EHsc /DWIN32 /D_WINDOWS /D_SCL_SECURE_NO_WARNINGS")
#set(CMAKE_CXX_FLAGS "/Zc:wchar_t /GR /EHsc /DNOCOLOR /DWIN32 /D_WINDOWS /D_SCL_SECURE_NO_WARNINGS") # XXX
else()
set (gcc_warnings_options "-Wall -Wextra -Wno-strict-aliasing")
# Clang has -Wno-bad-function-cast, but does not need it.
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
set (gcc_warnings_options "${gcc_warnings_options} -Wno-cast-function-type")
endif()
if(CMAKE_HOST_UNIX AND NOT CYGWIN)
add_definitions(-fPIC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${gcc_warnings_options} -fvisibility=hidden")
endif()
set(CMAKE_CXX_FLAGS_DEBUG "-g")
option(ENABLE_GCC_OPTIMIZATION "Enable specific GCC flags to optimization library \
size and performance. Only available on Release Mode" 0)
if(ENABLE_GCC_OPTIMIZATION)
set(CMAKE_CXX_FLAGS_RELEASE "-DNDEBUG -Os -Wl,-O1")
if(NOT CMAKE_HOST_APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wl,--hash-style=gnu")
endif()
endif()
if(CMAKE_HOST_APPLE)
# ALTERNATIVE_QT_INCLUDE_DIR is deprecated, because CMake takes care of finding the proper
# include folders using the qmake found in the environment. Only use it for now in case
# something goes wrong with the cmake process.
if(ALTERNATIVE_QT_INCLUDE_DIR AND NOT QT_INCLUDE_DIR)
set(QT_INCLUDE_DIR ${ALTERNATIVE_QT_INCLUDE_DIR})
endif()
endif()
endif()
endmacro()
function(qfp_strip_library target)
# Strip unless macOS (/strip: error: symbols referenced by indirect symbol
# table entries that can't be stripped).
if (CMAKE_STRIP AND UNIX AND NOT APPLE AND NOT QFP_NO_STRIP
AND NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
set(post_command COMMAND ${CMAKE_STRIP} $<TARGET_FILE:${target}>)
add_custom_command(TARGET ${target} POST_BUILD ${post_command})
endif()
endfunction()
macro(shiboken_internal_set_python_site_packages)
# When cross-building, we can't run the target python executable to find out the information,
# so we allow an explicit variable assignment or use a default / sensible value.
if(SHIBOKEN_IS_CROSS_BUILD OR PYSIDE_IS_CROSS_BUILD OR QFP_FIND_NEW_PYTHON_PACKAGE)
# Allow manual assignment.
if(QFP_PYTHON_SITE_PACKAGES)
set(PYTHON_SITE_PACKAGES "${QFP_PYTHON_SITE_PACKAGES}")
else()
# Assumes POSIX.
# Convention can be checked in cpython's source code in
# Lib/sysconfig.py's _INSTALL_SCHEMES
set(__version_major_minor
"${Python_VERSION_MAJOR}.${Python_VERSION_MINOR}")
set(PYTHON_SITE_PACKAGES_WITHOUT_PREFIX
"lib/python${__version_major_minor}/site-packages")
set(PYTHON_SITE_PACKAGES
"${CMAKE_INSTALL_PREFIX}/${PYTHON_SITE_PACKAGES_WITHOUT_PREFIX}")
unset(__version_major_minor)
endif()
else()
execute_process(
COMMAND ${Python_EXECUTABLE} -c "if True:
import sys
import sysconfig
from os.path import sep
# /home/qt/dev/env/lib/python3.9/site-packages
if sys.platform == 'win32':
lib_path = sysconfig.get_path('purelib')
else:
lib_path = sysconfig.get_path('purelib', scheme='posix_prefix')
# /home/qt/dev/env
if sys.platform == 'win32':
data_path = sysconfig.get_path('data')
else:
data_path = sysconfig.get_path('data', scheme='posix_prefix')
# /lib/python3.9/site-packages
rel_path = lib_path.replace(data_path, '')
print(f'${CMAKE_INSTALL_PREFIX}{rel_path}'.replace(sep, '/'))
"
OUTPUT_VARIABLE PYTHON_SITE_PACKAGES
OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
if (NOT PYTHON_SITE_PACKAGES)
message(FATAL_ERROR "Could not detect Python module installation directory.")
elseif (APPLE)
message(STATUS "!!! The generated bindings will be installed on ${PYTHON_SITE_PACKAGES}, \
is it right!?")
endif()
endmacro()
macro(set_python_config_suffix)
if (PYTHON_LIMITED_API)
if(WIN32)
set(PYTHON_EXTENSION_SUFFIX "")
else()
set(PYTHON_EXTENSION_SUFFIX ".abi3")
endif()
set(PYTHON_CONFIG_SUFFIX ".abi3")
else()
set(PYTHON_CONFIG_SUFFIX "${PYTHON_EXTENSION_SUFFIX}")
endif()
endmacro()
macro(setup_clang)
# Find libclang using the environment variables LLVM_INSTALL_DIR,
# CLANG_INSTALL_DIR using standard cmake.
# Use CLANG_INCLUDE_DIRS and link to libclang.
if(DEFINED ENV{LLVM_INSTALL_DIR})
list(PREPEND CMAKE_PREFIX_PATH "$ENV{LLVM_INSTALL_DIR}")
list(PREPEND CMAKE_FIND_ROOT_PATH "$ENV{LLVM_INSTALL_DIR}")
elseif(DEFINED ENV{CLANG_INSTALL_DIR})
list(PREPEND CMAKE_PREFIX_PATH "$ENV{CLANG_INSTALL_DIR}")
list(PREPEND CMAKE_FIND_ROOT_PATH "$ENV{CLANG_INSTALL_DIR}")
endif()
find_package(Clang CONFIG REQUIRED)
# Need to explicitly handle the version check, because the Clang package doesn't.
set(REQUIRED_LLVM "18.0")
if (LLVM_PACKAGE_VERSION AND LLVM_PACKAGE_VERSION VERSION_LESS "${REQUIRED_LLVM}")
message(WARNING "You need LLVM version ${REQUIRED_LLVM} or greater to build PySide "
"without issues, and ${LLVM_PACKAGE_VERSION} was found. "
"A lower version might case problems, specially on Windows.")
# Exception to enable Yocto builds (Kirkstone) - 6.8.x
set(REQUIRED_LLVM "14.0")
if (LLVM_PACKAGE_VERSION AND LLVM_PACKAGE_VERSION VERSION_LESS "${REQUIRED_LLVM}")
message(FATAL_ERROR "Using a LLVM version ${REQUIRED_LLVM} is the minimum allowed "
"to work pyside in some systems, however ${LLVM_PACKAGE_VERSION} was found.")
endif()
endif()
# CLANG_LIBRARY is read out from the cmake cache to deploy libclang
get_target_property(CLANG_BUILD_TYPE libclang IMPORTED_CONFIGURATIONS)
get_target_property(CLANG_LIBRARY_NAME libclang IMPORTED_LOCATION_${CLANG_BUILD_TYPE})
set(CLANG_LIBRARY "${CLANG_LIBRARY_NAME}" CACHE FILEPATH "libclang")
message(STATUS "CLANG: ${Clang_DIR}, ${CLANG_LIBRARY} detected")
endmacro()
macro(set_quiet_build)
# Don't display "up-to-date / install" messages when installing, to reduce visual clutter.
set(CMAKE_INSTALL_MESSAGE NEVER)
# Override message not to display info messages when doing a quiet build.
function(message)
list(GET ARGV 0 MessageType)
if (MessageType STREQUAL FATAL_ERROR OR
MessageType STREQUAL SEND_ERROR OR
MessageType STREQUAL WARNING OR
MessageType STREQUAL AUTHOR_WARNING)
list(REMOVE_AT ARGV 0)
_message(${MessageType} "${ARGV}")
endif()
endfunction()
endmacro()
macro(get_python_extension_suffix)
# When cross-building, we can't run the target python executable to find out the information,
# so we rely on Python_SOABI being set by find_package(Python).
# Python_SOABI is only set by CMake 3.17+
# TODO: Lower this to CMake 3.16 if possible.
if(SHIBOKEN_IS_CROSS_BUILD)
if(NOT Python_SOABI)
message(FATAL_ERROR "Python_SOABI variable is empty.")
endif()
set(PYTHON_EXTENSION_SUFFIX ".${Python_SOABI}")
else()
# See PYSIDE-1841 / https://bugs.python.org/issue39825 for distutils vs sysconfig
execute_process(
COMMAND ${Python_EXECUTABLE} -c "if True:
import sys
if sys.version_info >= (3, 8, 2):
import sysconfig
suffix = sysconfig.get_config_var('EXT_SUFFIX')
else:
from distutils import sysconfig
suffix = sysconfig.get_config_var('EXT_SUFFIX')
pos = suffix.rfind('.')
if pos > 0:
print(suffix[:pos])
else:
print(f'Unable to determine PYTHON_EXTENSION_SUFFIX from EXT_SUFFIX: \"{suffix}\"',
file=sys.stderr)
"
OUTPUT_VARIABLE PYTHON_EXTENSION_SUFFIX
OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
message(STATUS "PYTHON_EXTENSION_SUFFIX: " ${PYTHON_EXTENSION_SUFFIX})
endmacro()
macro(shiboken_parse_all_arguments prefix type flags options multiopts)
cmake_parse_arguments(${prefix} "${flags}" "${options}" "${multiopts}" ${ARGN})
if(DEFINED ${prefix}_UNPARSED_ARGUMENTS)
message(FATAL_ERROR "Unknown arguments were passed to ${type} (${${prefix}_UNPARSED_ARGUMENTS}).")
endif()
endmacro()
macro(shiboken_check_if_limited_api)
# TODO: Figure out how to use limited API libs when cross-building to Windows, if that's ever
# needed. Perhaps use host python to walk the libs of the target python installation.
if(NOT SHIBOKEN_IS_CROSS_BUILD AND WIN32)
# On Windows, PYTHON_LIBRARIES can be a list. Example:
# optimized;C:/Python36/libs/python36.lib;debug;C:/Python36/libs/python36_d.lib
# On other platforms, this result is not used at all.
execute_process(
COMMAND ${Python_EXECUTABLE} -c "if True:
from pathlib import Path
libs = r'${Python_LIBRARIES}'
libs = libs.split(';')
for lib in libs:
if ('\\\\' in lib or '/' in lib) and Path(lib).is_file():
lib = Path(lib)
prefix = lib.parent
py = lib.name
if py.startswith('python3'):
print(prefix / 'python3.lib')
break
"
OUTPUT_VARIABLE PYTHON_LIMITED_LIBRARIES
OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
message(STATUS "PYTHON_LIMITED_LIBRARIES: " ${PYTHON_LIMITED_LIBRARIES})
if(FORCE_LIMITED_API OR SHIBOKEN_PYTHON_LIMITED_API)
set(PYTHON_LIMITED_API 1)
if(WIN32)
set(SHIBOKEN_PYTHON_LIBRARIES ${PYTHON_LIMITED_LIBRARIES})
endif()
endif()
endmacro()
macro(shiboken_find_required_python)
set(_shiboken_find_python_version_args "")
if(${ARGC} GREATER 0)
list(APPEND _shiboken_find_python_version_args "${ARGV0}")
endif()
# This function can also be called by consumers of ShibokenConfig.cmake package like pyside,
# that's why we also check for PYSIDE_IS_CROSS_BUILD (which is set by pyside project)
# and QFP_FIND_NEW_PYTHON_PACKAGE for an explicit opt in.
#
# We have to use FindPython package instead of FindPythonInterp to get required target Python
# information.
if(SHIBOKEN_IS_CROSS_BUILD OR PYSIDE_IS_CROSS_BUILD OR QFP_FIND_NEW_PYTHON_PACKAGE)
# We want FindPython to look in the sysroot for the python-config executable,
# but toolchain files might set CMAKE_FIND_ROOT_PATH_MODE_PROGRAM to NEVER because
# programs are mostly found for running and you usually can't run a target executable on
# a host platform. python-config can likely be ran though, because it's a shell script
# to be run on a host Linux.
set(_shiboken_backup_CMAKE_FIND_ROOT_PATH_MODE_PROGRAM
"${CMAKE_FIND_ROOT_PATH_MODE_PROGRAM}")
set(_shiboken_backup_CMAKE_FIND_ROOT_PATH
"${CMAKE_FIND_ROOT_PATH}")
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY)
if(Python_ROOT_DIR)
list(PREPEND CMAKE_FIND_ROOT_PATH "${Python_ROOT_DIR}")
endif()
# We can't look for the Python interpreter because FindPython tries to execute it, which
# usually won't work on a host platform due to different architectures / platforms.
# Thus we only look for the Python include and lib directories which are part of the
# Development component.
find_package(
Python
${_shiboken_find_python_version_args}
REQUIRED
COMPONENTS Development
)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM
"${_shiboken_backup_CMAKE_FIND_ROOT_PATH_MODE_PROGRAM}")
set(CMAKE_FIND_ROOT_PATH
"${_shiboken_backup_CMAKE_FIND_ROOT_PATH}")
# For Android platform sometimes the FindPython module returns Python_SOABI as empty in
# certain scenarios eg: armv7a target, macOS host etc. This is because
# it is unable to set Python_CONFIG i.e. `python3-config` script
# This workaround sets the Python_SOABI manually for this Android platform.
# This needs to be updated manually if the Python version for Android cross compilation
# changes.
# TODO: Find a better way to set Python_SOABI for Android platform
if(CMAKE_SYSTEM_NAME STREQUAL "Android" AND NOT Python_SOABI)
set(Python_SOABI "cpython-311")
endif()
else()
find_package(
Python
${_shiboken_find_python_version_args}
REQUIRED
COMPONENTS Interpreter Development.Module
)
endif()
shiboken_validate_python_version()
set(SHIBOKEN_PYTHON_INTERPRETER "${Python_EXECUTABLE}")
set_property(GLOBAL PROPERTY SHIBOKEN_PYTHON_INTERPRETER "${Python_EXECUTABLE}")
endmacro()
macro(shiboken_validate_python_version)
if(Python_VERSION_MAJOR EQUAL "3" AND Python_VERSION_MINOR LESS "9")
message(FATAL_ERROR
"Shiboken requires Python 3.9+.")
endif()
endmacro()
macro(shiboken_compute_python_includes)
shiboken_parse_all_arguments(
"SHIBOKEN_COMPUTE_INCLUDES" "shiboken_compute_python_includes"
"IS_CALLED_FROM_EXPORT" "" "" ${ARGN})
# If the installed shiboken config file is used,
# append the found Python include dirs as an interface property on the libshiboken target.
# This needs to be dynamic because the user of the library might have python installed
# in a different path than when shiboken was originally built.
# Otherwise if shiboken is currently being built itself (either as standalone, or super project
# build) append the include dirs as PUBLIC.
if (SHIBOKEN_COMPUTE_INCLUDES_IS_CALLED_FROM_EXPORT)
#TODO target_include_directories works on imported targets only starting with v3.11.0.
set_property(TARGET Shiboken6::libshiboken
APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${Python_INCLUDE_DIRS})
else()
target_include_directories(libshiboken
PUBLIC $<BUILD_INTERFACE:${Python_INCLUDE_DIRS}>)
endif()
set(SHIBOKEN_PYTHON_INCLUDE_DIRS "${Python_INCLUDE_DIRS}")
set_property(GLOBAL PROPERTY shiboken_python_include_dirs "${SHIBOKEN_PYTHON_INCLUDE_DIRS}")
message(STATUS
"SHIBOKEN_PYTHON_INCLUDE_DIRS computed to value: '${SHIBOKEN_PYTHON_INCLUDE_DIRS}'")
endmacro()
# Given a list of the following form:
# optimized;C:/Python36/libs/python36.lib;debug;C:/Python36/libs/python36_d.lib
# choose the corresponding library to use, based on the current configuration type.
function(shiboken_get_library_for_current_config library_list current_config out_var)
list(FIND library_list "optimized" optimized_found)
list(FIND library_list "general" general_found)
list(FIND library_list "debug" debug_found)
if (optimized_found OR general_found OR debug_found)
# Iterate over library list to find the most appropriate library.
foreach(token ${library_list})
if(token STREQUAL "optimized" OR token STREQUAL "general")
set(is_debug 0)
set(token1 1)
set(lib "")
elseif(token STREQUAL "debug")
set(is_debug 1)
set(token1 1)
set(lib "")
elseif(EXISTS ${token})
set(lib ${token})
set(token2 1)
else()
set(token1 0)
set(token2 0)
set(lib "")
endif()
if(token1 AND token2)
if((is_debug AND lib AND current_config STREQUAL "Debug")
OR (NOT is_debug AND lib AND (NOT current_config STREQUAL "Debug")))
set(${out_var} ${lib} PARENT_SCOPE)
return()
endif()
endif()
endforeach()
else()
# No configuration specific libraries found, just set the original value.
set(${out_var} "${library_list}" PARENT_SCOPE)
endif()
endfunction()
macro(shiboken_compute_python_libraries)
shiboken_parse_all_arguments(
"SHIBOKEN_COMPUTE_LIBS" "shiboken_compute_python_libraries"
"IS_CALLED_FROM_EXPORT" "" "" ${ARGN})
if (NOT SHIBOKEN_PYTHON_LIBRARIES)
set(SHIBOKEN_PYTHON_LIBRARIES "")
endif()
if(WIN32 AND NOT SHIBOKEN_PYTHON_LIBRARIES)
set(SHIBOKEN_PYTHON_LIBRARIES ${Python_LIBRARIES})
endif()
# If the resulting variable
# contains a "debug;X;optimized;Y" list like described in shiboken_check_if_limited_api,
# make sure to pick just one, so that the final generator expressions are valid.
shiboken_get_library_for_current_config("${SHIBOKEN_PYTHON_LIBRARIES}" "${CMAKE_BUILD_TYPE}" "SHIBOKEN_PYTHON_LIBRARIES")
if(APPLE)
set(SHIBOKEN_PYTHON_LIBRARIES "-undefined dynamic_lookup")
endif()
# If the installed shiboken config file is used,
# append the computed Python libraries as an interface property on the libshiboken target.
# This needs to be dynamic because the user of the library might have python installed
# in a different path than when shiboken was originally built.
# Otherwise if shiboken is currently being built itself (either as standalone, or super project
# build) append the libraries as PUBLIC.
if (SHIBOKEN_COMPUTE_LIBS_IS_CALLED_FROM_EXPORT)
#TODO target_link_libraries works on imported targets only starting with v3.11.0.
set_property(TARGET Shiboken6::libshiboken
APPEND PROPERTY INTERFACE_LINK_LIBRARIES ${SHIBOKEN_PYTHON_LIBRARIES})
else()
target_link_libraries(libshiboken
PUBLIC $<BUILD_INTERFACE:${SHIBOKEN_PYTHON_LIBRARIES}>)
endif()
set_property(GLOBAL PROPERTY shiboken_python_libraries "${SHIBOKEN_PYTHON_LIBRARIES}")
message(STATUS "SHIBOKEN_PYTHON_LIBRARIES computed to value: '${SHIBOKEN_PYTHON_LIBRARIES}'")
endmacro()
function(shiboken_check_if_built_and_target_python_are_compatible)
if(NOT SHIBOKEN_PYTHON_VERSION_MAJOR STREQUAL Python_VERSION_MAJOR)
message(FATAL_ERROR "The detected Python major version is not \
compatible with the Python major version which was used when Shiboken was built.
Built with: '${SHIBOKEN_PYTHON_VERSION_MAJOR}.${SHIBOKEN_PYTHON_VERSION_MINOR}' \
Detected: '${Python_VERSION_MAJOR}.${Python_VERSION_MINOR}'")
else()
if(NOT SHIBOKEN_PYTHON_LIMITED_API
AND NOT SHIBOKEN_PYTHON_VERSION_MINOR STREQUAL Python_VERSION_MINOR)
message(FATAL_ERROR
"The detected Python minor version is not compatible with the Python minor \
version which was used when Shiboken was built. Consider building shiboken with \
FORCE_LIMITED_API set to '1', so that only the Python major version matters.
Built with: '${SHIBOKEN_PYTHON_VERSION_MAJOR}.${SHIBOKEN_PYTHON_VERSION_MINOR}' \
Detected: '${Python_VERSION_MAJOR}.${Python_VERSION_MINOR}'")
endif()
endif()
endfunction()
function(shiboken_internal_disable_pkg_config)
# Disable pkg-config by setting an empty executable path. There's no documented way to
# mark the package as not found, but we can force all pkg_check_modules calls to do nothing
# by setting the variable to an empty value.
set(PKG_CONFIG_EXECUTABLE "" CACHE STRING "Disabled pkg-config usage." FORCE)
endfunction()
function(shiboken_internal_disable_pkg_config_if_needed)
if(SHIBOKEN_SKIP_PKG_CONFIG_ADJUSTMENT)
return()
endif()
# pkg-config should not be used by default on Darwin platforms.
if(APPLE)
set(pkg_config_enabled OFF)
else()
set(pkg_config_enabled ON)
endif()
if(NOT pkg_config_enabled)
shiboken_internal_disable_pkg_config()
endif()
endfunction()
function(shiboken_internal_detect_if_cross_building)
if(CMAKE_CROSSCOMPILING OR QFP_SHIBOKEN_HOST_PATH)
set(is_cross_build TRUE)
else()
set(is_cross_build FALSE)
endif()
set(SHIBOKEN_IS_CROSS_BUILD "${is_cross_build}" PARENT_SCOPE)
message(STATUS "SHIBOKEN_IS_CROSS_BUILD: ${is_cross_build}")
endfunction()
function(shiboken_internal_decide_parts_to_build)
set(build_libs_default ON)
option(SHIBOKEN_BUILD_LIBS "Build shiboken libraries" ${build_libs_default})
message(STATUS "SHIBOKEN_BUILD_LIBS: ${SHIBOKEN_BUILD_LIBS}")
if(SHIBOKEN_IS_CROSS_BUILD)
set(build_tools_default OFF)
else()
set(build_tools_default ON)
endif()
option(SHIBOKEN_BUILD_TOOLS "Build shiboken tools" ${build_tools_default})
message(STATUS "SHIBOKEN_BUILD_TOOLS: ${SHIBOKEN_BUILD_TOOLS}")
if(SHIBOKEN_IS_CROSS_BUILD)
set(_shiboken_build_tests_default OFF)
elseif(SHIBOKEN_BUILD_LIBS)
set(_shiboken_build_tests_default ON)
endif()
option(BUILD_TESTS "Build tests." ${_shiboken_build_tests_default})
message(STATUS "BUILD_TESTS: ${BUILD_TESTS}")
endfunction()
function(shiboken_internal_find_host_shiboken_tools)
if(SHIBOKEN_IS_CROSS_BUILD)
set(find_package_extra_args)
if(QFP_SHIBOKEN_HOST_PATH)
list(APPEND find_package_extra_args PATHS "${QFP_SHIBOKEN_HOST_PATH}/lib/cmake")
list(PREPEND CMAKE_FIND_ROOT_PATH "${QFP_SHIBOKEN_HOST_PATH}")
endif()
find_package(
Shiboken6Tools 6 CONFIG
${find_package_extra_args}
)
if(NOT Shiboken6Tools_DIR)
message(FATAL_ERROR
"Shiboken6Tools package was not found. "
"Please set QFP_SHIBOKEN_HOST_PATH to the location where the Shiboken6Tools CMake "
"package is installed.")
endif()
endif()
endfunction()
function(shiboken_internal_set_up_extra_dependency_paths)
set(extra_root_path_vars
QFP_QT_TARGET_PATH
QFP_PYTHON_TARGET_PATH
)
foreach(root_path IN LISTS extra_root_path_vars)
set(new_root_path_value "${${root_path}}")
if(new_root_path_value)
set(new_prefix_path "${CMAKE_PREFIX_PATH}")
list(PREPEND new_prefix_path "${new_root_path_value}/lib/cmake")
set(CMAKE_PREFIX_PATH "${new_prefix_path}")
set(CMAKE_PREFIX_PATH "${new_prefix_path}" PARENT_SCOPE)
# Need to adjust the prefix and root paths so that find_package(Qt) and other 3rd
# party packages are found successfully when they are located outside of the
# default sysroot (whatever that maybe for the target platform).
if(SHIBOKEN_IS_CROSS_BUILD)
set(new_root_path "${CMAKE_FIND_ROOT_PATH}")
list(PREPEND new_root_path "${new_root_path_value}")
set(CMAKE_FIND_ROOT_PATH "${new_root_path}")
set(CMAKE_FIND_ROOT_PATH "${new_root_path}" PARENT_SCOPE)
endif()
endif()
endforeach()
endfunction()
macro(compute_config_py_values
full_version_var_name
)
set(QT_MACOS_DEPLOYMENT_TARGET "")
if (Qt${QT_MAJOR_VERSION}Core_FOUND)
get_target_property(darwin_target Qt6::Core QT_DARWIN_MIN_DEPLOYMENT_TARGET)
if(darwin_target)
set(QT_MACOS_DEPLOYMENT_TARGET
"__qt_macos_min_deployment_target__ = '${darwin_target}'")
endif()
elseif(APPLE)
message(FATAL_ERROR "Qt6::Core should be found before calling this macro")
endif()
string(TIMESTAMP PACKAGE_BUILD_DATE "%Y-%m-%dT%H:%M:%S+00:00" UTC)
if (PACKAGE_BUILD_DATE)
set(PACKAGE_BUILD_DATE "__build_date__ = '${PACKAGE_BUILD_DATE}'")
endif()
if (PACKAGE_SETUP_PY_PACKAGE_VERSION)
set(PACKAGE_SETUP_PY_PACKAGE_VERSION_ASSIGNMENT "__setup_py_package_version__ = '${PACKAGE_SETUP_PY_PACKAGE_VERSION}'")
set(FINAL_PACKAGE_VERSION ${PACKAGE_SETUP_PY_PACKAGE_VERSION})
else()
set(FINAL_PACKAGE_VERSION ${${full_version_var_name}})
endif()
if (PACKAGE_SETUP_PY_PACKAGE_TIMESTAMP)
set(PACKAGE_SETUP_PY_PACKAGE_TIMESTAMP_ASSIGNMENT "__setup_py_package_timestamp__ = '${PACKAGE_SETUP_PY_PACKAGE_TIMESTAMP}'")
else()
set(PACKAGE_SETUP_PY_PACKAGE_TIMESTAMP_ASSIGNMENT "")
endif()
find_package(Git)
if(GIT_FOUND)
# Check if current source folder is inside a git repo, so that commit information can be
# queried.
execute_process(
COMMAND ${GIT_EXECUTABLE} rev-parse --git-dir
OUTPUT_VARIABLE PACKAGE_SOURCE_IS_INSIDE_REPO
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(PACKAGE_SOURCE_IS_INSIDE_REPO)
# Force git dates to be UTC-based.
set(ENV{TZ} UTC)
execute_process(
COMMAND ${GIT_EXECUTABLE} --no-pager show --date=format-local:%Y-%m-%dT%H:%M:%S+00:00 -s --format=%cd HEAD
OUTPUT_VARIABLE PACKAGE_BUILD_COMMIT_DATE
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(PACKAGE_BUILD_COMMIT_DATE)
set(PACKAGE_BUILD_COMMIT_DATE "__build_commit_date__ = '${PACKAGE_BUILD_COMMIT_DATE}'")
endif()
unset(ENV{TZ})
execute_process(
COMMAND ${GIT_EXECUTABLE} rev-parse HEAD
OUTPUT_VARIABLE PACKAGE_BUILD_COMMIT_HASH
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(PACKAGE_BUILD_COMMIT_HASH)
set(PACKAGE_BUILD_COMMIT_HASH "__build_commit_hash__ = '${PACKAGE_BUILD_COMMIT_HASH}'")
endif()
execute_process(
COMMAND ${GIT_EXECUTABLE} describe HEAD
OUTPUT_VARIABLE PACKAGE_BUILD_COMMIT_HASH_DESCRIBED
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(PACKAGE_BUILD_COMMIT_HASH_DESCRIBED)
set(PACKAGE_BUILD_COMMIT_HASH_DESCRIBED "__build_commit_hash_described__ = '${PACKAGE_BUILD_COMMIT_HASH_DESCRIBED}'")
endif()
endif()
endif()
endmacro()
# Creates a new target called "${library_name}_generator" which
# depends on the mjb_rejected_classes.log file generated by shiboken.
# This target is added as a dependency to ${library_name} target.
# This file's timestamp informs cmake when the last generation was
# done, without force-updating the timestamps of the generated class
# cpp files.
# In practical terms this means that changing some injection code in
# an xml file that modifies only one specific class cpp file, will
# not force rebuilding all the cpp files, and thus allow for better
# incremental builds.
macro(create_generator_target library_name)
add_custom_target(${library_name}_generator DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/mjb_rejected_classes.log")
add_dependencies(${library_name} ${library_name}_generator)
endmacro()
# Generate a shell script wrapper that sets environment variables for executing a specific tool.
#
# tool_name should be a unique tool name, preferably without spaces.
# Returns the wrapper path in path_out_var.
#
# Currently adds the Qt lib dir and libclang to PATH / LD_LIBRARY_PATH / DYLD_LIBRARY_PATH.
# Meant to be used as the first argument to add_custom_command's COMMAND option.
# TODO: Remove tool_name as the tool_name for this function is always shiboken.
function(shiboken_get_tool_shell_wrapper tool_name path_out_var)
# Generate the wrapper only once during the execution of CMake.
get_property(is_called GLOBAL PROPERTY "_shiboken_tool_wrapper_${tool_name}_created")
if(is_called)
get_property(wrapper_path GLOBAL PROPERTY "_shiboken_tool_wrapper_${tool_name}_path")
set(${path_out_var} "${wrapper_path}" PARENT_SCOPE)
return()
endif()
set(path_dirs "")
set(path_dirs_native "")
if(CMAKE_HOST_WIN32)
set(wrapper_script_extension ".bat")
else()
set(wrapper_script_extension ".sh")
endif()
# Try to get original host shiboken paths from exported target properties.
shiboken_get_host_tool_wrapper_properties(orig_qt_library_dir_absolute orig_libclang_lib_dir)
# Get path to the Qt bin/lib dir depending on the platform and developer input.
# Prefer values given on the command line, then the original host path if it exists, otherwise
# try to use the Qt install prefix and libclang env vars.
#
# Note that in a cross-compiling case, using the Qt install prefix is very likely
# wrong, because you want to use the location of the host Qt, not the target Qt. Same for
# libclang. Unfortunately we currently don't provide a host Qt and host libclang option via
# setup.py, so the manual cmake vars will have to suffice.
if(SHIBOKEN_WRAPPER_HOST_QT_LIB_PATH AND EXISTS "${SHIBOKEN_WRAPPER_HOST_QT_LIB_PATH}")
set(qt_library_dir_absolute "${SHIBOKEN_WRAPPER_HOST_QT_LIB_PATH}")
elseif(orig_qt_library_dir_absolute AND EXISTS "${orig_qt_library_dir_absolute}")
set(qt_library_dir_absolute "${orig_qt_library_dir_absolute}")
elseif(CMAKE_HOST_WIN32)
# in Windows the Qt dll are store `bin` in directory
set(qt_library_dir ${QT6_INSTALL_BINS})
else()
# in Unix the .so are stored in `lib` directory
set(qt_library_dir ${QT6_INSTALL_LIBS})
endif()
# Assert that Qt is already found.
if((QT6_INSTALL_PREFIX AND qt_library_dir) OR orig_qt_library_dir_absolute)
else()
message(FATAL_ERROR "Qt should have been found already by now.")
endif()
if(NOT qt_library_dir_absolute)
set(qt_library_dir_absolute "${QT6_INSTALL_PREFIX}/${qt_library_dir}")
endif()
list(APPEND path_dirs "${qt_library_dir_absolute}")
# Get libclang lib dir path.
# Prefer values given on the command line, then the original host path if it exists.
if(SHIBOKEN_WRAPPER_HOST_CLANG_LIB_PATH AND EXISTS "${SHIBOKEN_WRAPPER_HOST_CLANG_LIB_PATH}")
set(libclang_lib_dir "${SHIBOKEN_WRAPPER_HOST_CLANG_LIB_PATH}")
elseif(orig_libclang_lib_dir AND EXISTS "${orig_libclang_lib_dir}")
set(libclang_lib_dir "${orig_libclang_lib_dir}")
else()
# find libclang
find_libclang()
endif()
if(libclang_lib_dir)
list(APPEND path_dirs "${libclang_lib_dir}")
endif()
# Convert the paths from unix-style to native Windows style.
foreach(path_dir IN LISTS path_dirs)
if(EXISTS "${path_dir}")
file(TO_NATIVE_PATH "${path_dir}" path_dir_native)
list(APPEND path_dirs_native "${path_dir_native}")
endif()
endforeach()
set(wrapper_dir "${CMAKE_BINARY_DIR}/.qfp/bin")
file(MAKE_DIRECTORY "${wrapper_dir}")
set(wrapper_path "${wrapper_dir}/${tool_name}_wrapper${wrapper_script_extension}")
if(CMAKE_HOST_WIN32)
file(WRITE "${wrapper_path}" "@echo off
set PATH=${path_dirs_native};%PATH%
%*")
elseif(CMAKE_HOST_APPLE)
string(REPLACE ";" ":" path_dirs_native "${path_dirs_native}")
file(WRITE "${wrapper_path}" "#!/bin/bash
export DYLD_LIBRARY_PATH=${path_dirs_native}:$DYLD_LIBRARY_PATH
export DYLD_FRAMEWORK_PATH=${path_dirs_native}:$DYLD_FRAMEWORK_PATH
$@")
else()
string(REPLACE ";" ":" path_dirs_native "${path_dirs_native}")
file(WRITE "${wrapper_path}" "#!/bin/bash
export LD_LIBRARY_PATH=${path_dirs_native}:$LD_LIBRARY_PATH
$@")
endif()
# Remember the creation of the file for a specific tool.
set_property(GLOBAL PROPERTY "_shiboken_tool_wrapper_${tool_name}_path" "${wrapper_path}")
set_property(GLOBAL PROPERTY "_shiboken_tool_wrapper_${tool_name}_created" TRUE)
# Save original host paths for future cross-builds.
shiboken_save_host_tool_wrapper_properties("${qt_library_dir_absolute}" "${libclang_lib_dir}")
# give execute permission to run the file
if(CMAKE_HOST_UNIX)
execute_process(COMMAND chmod +x ${wrapper_path})
endif()
set(${path_out_var} "${wrapper_path}" PARENT_SCOPE)
endfunction()
# Retrieve the original host shiboken runtime dependency paths from the installed (namespaced)
# shiboken generator target.
function(shiboken_get_host_tool_wrapper_properties out_qt_library_dir out_libclang_lib_dir)
if(TARGET Shiboken6::shiboken6)
get_target_property(qt_library_dir Shiboken6::shiboken6 _shiboken_original_qt_lib_dir)
if(NOT qt_library_dir)
set(qt_library_dir "")
endif()
get_target_property(libclang_lib_dir Shiboken6::shiboken6
_shiboken_original_libclang_lib_dir)
if(NOT libclang_lib_dir)
set(libclang_lib_dir "")
endif()
endif()
set(${out_qt_library_dir} "${qt_library_dir}" PARENT_SCOPE)
set(${out_libclang_lib_dir} "${libclang_lib_dir}" PARENT_SCOPE)
endfunction()
# Save original host shiboken runtime dependency paths as target properties, so they can be used
# when generating the wrapper file for cross-builds.
# Should only be done when shiboken is being built (aka it's a non-imported target).
function(shiboken_save_host_tool_wrapper_properties qt_library_dir libclang_lib_dir)
if(TARGET shiboken6)
get_target_property(is_imported shiboken6 IMPORTED)
if(is_imported)
return()
endif()
set_target_properties(shiboken6 PROPERTIES
_shiboken_original_qt_lib_dir "${qt_library_dir}")
set_property(TARGET shiboken6 APPEND PROPERTY
EXPORT_PROPERTIES _shiboken_original_qt_lib_dir)
if(libclang_lib_dir)
set_target_properties(shiboken6 PROPERTIES
_shiboken_original_libclang_lib_dir "${libclang_lib_dir}")
set_property(TARGET shiboken6 APPEND PROPERTY
EXPORT_PROPERTIES _shiboken_original_libclang_lib_dir)
endif()
endif()
endfunction()
# Returns the platform-specific relative rpath base token, if it's supported.
# If it's not supported, returns the string NO_KNOWN_RPATH_REL_BASE.
function(get_rpath_base_token out_var)
if(APPLE)
set(rpath_rel_base "@loader_path")
elseif(UNIX)
set(rpath_rel_base "$ORIGIN")
else()
#has no effect on Windows
set(rpath_rel_base "NO_KNOWN_RPATH_REL_BASE")
endif()
set(${out_var} "${rpath_rel_base}" PARENT_SCOPE)
endfunction()
# Get path to libclang.dll/libclang.so depending on the platform
macro(find_libclang)
find_package(Clang CONFIG REQUIRED)
get_target_property(libclang_location libclang LOCATION)
get_filename_component(libclang_lib_dir "${libclang_location}" DIRECTORY)
endmacro()
# Allow setting a shiboken debug level from the the build system or from the environment
# to all shiboken invocations.
function(shiboken_get_debug_level out_var)
set(debug_level "")
if(SHIBOKEN_DEBUG_LEVEL)
set(debug_level "--debug-level=${SHIBOKEN_DEBUG_LEVEL}")
elseif(DEFINED ENV{SHIBOKEN_DEBUG_LEVEL})
set(debug_level "--debug-level=$ENV{SHIBOKEN_DEBUG_LEVEL}")
endif()
set(${out_var} "${debug_level}" PARENT_SCOPE)
endfunction()

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1 @@
# this is a marker file for mypy

Binary file not shown.

Binary file not shown.