如何在Python中实现Swift或ObjectiveC的可变指针?

2024-09-27 00:11:57 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的函数需要一个“可变指针”。我如何用Python表示它?你知道吗

银行代码:

func CGPDFDocumentGetVersion(
  _ document: CGPDFDocument?,
  _ majorVersion: UnsafeMutablePointer<Int32>,
  _ minorVersion: UnsafeMutablePointer<Int32>
)

目标C:

void CGPDFDocumentGetVersion (
  CGPDFDocumentRef document,
  int *majorVersion,
  int *minorVersion
);

尽管如此,函数以这种方式返回值似乎有点疯狂。你知道吗

我试着只提供变量,已经分配给空值,但我得到一个分段错误。如果变量未定义,我得到:

NameError: name 'x' is not defined

下面是一些导致Sgmentation错误的代码。如果CoreGraphics不喜欢输入,那么很容易得到这些。你知道吗

file = "/path/to/file.pdf"
pdf = CGPDFDocumentCreateWithProvider(CGDataProviderCreateWithFilename(file))
x = None
y = None
version = CGPDFDocumentGetVersion(pdf, x, y)

Tags: 函数代码nonepdf错误银行documentfile
1条回答
网友
1楼 · 发布于 2024-09-27 00:11:57

你根本不需要可变指针。类C代码中指向int(或类似存储)的指针有两种常见用法,Python提供了两种更好的方法。你知道吗

案例1:多个返回值

如果不定义一个新的struct并为其分配内存,类C函数不能返回多个值。这已经够乏味了,作业常常被强加给调用函数,调用函数提供指向它预先分配的存储的指针。你知道吗

在Python中,只需返回一个对象。。。在您的例子中,tuple^{}

import collections

Version = collections.namedtuple(
  'Version',
  ('major', 'minor'),
  )

class PDFDocument:

    def __init__(self, ...):
        # Figure out major and minor version numbers, then...
        self.version = Version(major, minor)

pdf_doc = PDFDocument(...)
major, minor = pdf_doc.version
...

案例2:宣布错误

一个需要发出错误发生信号的类C函数通常会返回一些“非法”值。如果没有可以使用的值,另一种方法是使用一个指向调用者拥有的某个存储的指针,在那里调用者将在退出时涂鸦其退出状态。你知道吗

在Python中,您只需要raise一个异常,这个异常在几乎所有方面都更好。你知道吗

相关问题 更多 >

    热门问题