[英]Use C const variable in Swift as UnsafePointer
我在.h / c文件中有一個簡單的C const變量,如下所示:
const float positions[9];
#include "data.h"
const float positions[9] = {
1.0, -1.0, 1.0,
-1.0, -1.0, 1.0,
-1.0, -1.0, -1.0,
};
如何在Swift中使用此變量的數據? 更具體地說,我需要將數據傳遞給glVertexAttribPointer(,,,,, <#ptr: UnsafePointer<Void>#>)
。
例如,我在Swift中有以下代碼:(我在橋接頭中添加了data.h ):
glEnableVertexAttribArray(0)
glVertexAttribPointer(0, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 0, positions)
// Error: '(Float, Float, Float, Float, Float, Float, Float, Float, Float)' is not convertible to 'UnsafePointer<Void>'
glDrawArrays(GLenum(GL_TRIANGLES), 0, 3)
我得到的錯誤是'((Float,Float,Float,Float,Float,Float,Float,Float,Float)'無法轉換為'UnsafePointer <Void>' 。
我應該指出,這只是一個測試應用程序,因此我沒有使用VBO( 清單8-2 )。
事實證明,靜態分配的C數組作為元組進入Swift。 使用指針變量可以解決此問題。
在C中: const float positions[9];
轉換為
let positions: (Float, Float, Float, Float, Float, Float, Float, Float, Float)
Swift中的let positions: (Float, Float, Float, Float, Float, Float, Float, Float, Float)
在C中: const float *positions;
轉換為
var positions: UnsafePointer<Float>
Swift中的var positions: UnsafePointer<Float>
(這是我們需要的)
因此,按如下所示修改C文件就可以了:
const float *positions;
#include "data.h"
const float _positions[9] = {
1.0, -1.0, 1.0,
-1.0, -1.0, 1.0,
-1.0, -1.0, -1.0,
};
const float *positions = _positions;
glVertexAttribPointer(0, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 0, positions)
在Swift中將數組作為元組看起來很奇怪,如果有人對此有任何想法,我將不勝感激。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.