How do I dynamically create an array at runtime in Objective-C (iOS)? - ios4

I have recently started doing some things in my iOS app using OpenGL.
I found this tutorial which has been a tremendous help:
www.raywenderlich.com/3664/opengl-es-2-0-for-iphone-tutorial .
typedef struct
{
float Position[3];
float Color[4];
} Vertex;
const Vertex Vertices[] = { ... };
const GLubyte Indices[] = { ... };
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Indices), Indices, GL_STATIC_DRAW);
I need an array of variables/structs since the content is dependent on what happens at runtime and is not static.
How do I define and create a dynamic array when I don't know the number of elements in the array until runtime?
Do I need to use malloc or something like that? I haven't come across any examples of allocating memory for an iPhone app before so I'm a little wary. Any advice or direction would be appreciated.

With malloc:
Vertex* verts;
void Load()
{
int SIZE=200;
verts=(Vertex*)malloc(sizeof(Vertex)*SIZE);//in c you dont need (Vertex*)
}

Related

Passing a std::unique_ptr to CListBox::GetSelItems

I have seen a great answer here which has helped me to a great extent (Proper way to create unique_ptr that holds an allocated array) but I still have an issue.
Code:
void CSelectedBroHighlight::BuildSelectedArray()
{
CString strText;
// empty current array
m_aryStrSelectedBro.RemoveAll();
// get selected count
const auto iSize = m_lbBrothers.GetSelCount();
if(iSize > 0)
{
//auto pIndex = std::make_unique<int[]>(iSize);
auto pIndex = new int[iSize];
m_lbBrothers.GetSelItems(iSize, pIndex);
for(auto i = 0; i < iSize; i++)
{
m_lbBrothers.GetText(pIndex[i], strText);
m_aryStrSelectedBro.Add(strText);
}
delete[] pIndex;
}
}
If I turn pIndex into a smart pointer:
auto pIndex = std::make_unique<int[]>(iSize);
So that I don't need the delete[] pIndex; call. Then I can't pass pIndex to GetSelItems. I can pass pIndex.release() here but then we have a problem for deleting again.
I have looked at this discussion (Issue passing std::unique_ptr's) but we don't want to pass ownership.
If I simplify this and declar my variable: auto pIndex = std::make_unique<int[]>(iSize).release(); then I can pass it, but now have the issue of calling delete[] pIndex;.
Whats correct?
If you need access to the pointer to an object managed by a std::unique_ptr without transferring ownership, you can call its get() method. This is useful for interop with a C interface such as here (GetSelItems() is really just wrapping a call to SendMessage with the LB_GETSELITEMS message).
That'd work, though in this case I'd probably use a std::vector<int> instead. It provides the same properties as a std::unique_ptr with respect to automatic cleanup, but also has other features that come in handy (specifically range adapters). It also feels more natural to use a container here, but that's a matter of personal preference.
The following implements the proposed changes:
void CSelectedBroHighlight::BuildSelectedArray() {
// empty current array
m_aryStrSelectedBro.RemoveAll();
// get selected count
auto const sel_item_count{ m_lbBrothers.GetSelCount() };
if(sel_item_count > 0) {
// get selected indices
std::vector<int> sel_items(sel_item_count);
m_lbBrothers.GetSelItems(sel_items.size(), sel_items.data());
// iterate over all selected item indices
for(auto const index : sel_items) {
CString strText;
m_lbBrothers.GetText(index, strText);
m_aryStrSelectedBro.Add(strText);
}
}
}
This provides the same automatic cleanup as an implementation based on std::unique_ptr, but also enables use of a range-based for loop further down.

Create Uniform Buffers in Vulkan

i hava a problem with drawing meshes in Vulkan.
I want to bind a UniformBufferObject in the following form to a Object.
void mainLoop() {
..
vulkanDrawing.Draw();
plane.UpdateUniformBuffers();
..
}
To get the currentImage, I created a method SetCurrentImage(uint32_t currentImage).
SetCurrentImage is set from VulkanDrawing::Draw() Method.
This current image is used in the UpdateUniformBuffers().
I get only a black screen if I run this application.
Since, I want to see a square.
In the past, I called the UpdateUniformBuffers Method with an imageIndex parameter in VulkanDrawing::Draw().
I think it could be a problem with the fences or semaphores. But I don't know how I shall fix it.
Does I use eventually a wrong Architecture?
I have attached important Methods:
void CVulkanDrawing::Draw()
{
vkWaitForFences(m_LogicalDevice.getDevice(), 1, &inFlightFences[currentFrame], VK_TRUE, std::numeric_limits<uint64_t>::max());
vkResetFences(m_LogicalDevice.getDevice(), 1,inFlightFences[currentFrame]);
uint32_t imageIndex;
vkAcquireNextImageKHR(m_LogicalDevice.getDevice(), m_Presentation.GetSwapChain(), std::numeric_limits<uint64_t>::max(), imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
for(unsigned int i = 0; i < m_VulkanMesh.size(); i++)
{
//m_VulkanMesh.at(i).UpdateUniformBuffers(imageIndex);
m_VulkanMesh.at(i).SetCurrentImage(imageIndex);
}
VkSubmitInfo submitInfo = {};
...
currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
}
void CVulkanMesh::UpdateUniformBuffers()
{
...
vkMapMemory(m_LogicalDevice.getDevice(), uniformBuffersMemory[this->m_CurrentImage], 0, sizeof(ubo), 0, &data);
memcpy(data, &ubo, sizeof(ubo));
vkUnmapMemory(m_LogicalDevice.getDevice(), uniformBuffersMemory[this->m_CurrentImage]);
}
void CVulkanMesh::SetCurrentImage(uint32_t currentImage)
{
this->m_CurrentImage = currentImage;
}
I have additionally created a branch named: https://github.com/dekorlp/VulkanWrapper/tree/VulkanTest
I hope you can help me :)
Best regards
Pixma

Why is the struct unknown at compiletime in the code?

I was wondering how I could change the code below such the bmBc is computed at compile time . The one below works for runtime but it is not ideal since I need to know the bmBc table at compile-time . I could appreciate advice on how I could improve on this.
import std.conv:to;
import std.stdio;
int [string] bmBc;
immutable string pattern = "GCAGAGAG";
const int size = to!int(pattern.length);
struct king {
void calculatebmBc(int i)()
{
static if ( i < size -1 )
bmBc[to!string(pattern[i])]=to!int(size-i-1);
// bmBc[pattern[i]] ~= i-1;
calculatebmBc!(i+1)();
}
void calculatebmBc(int i: size-1)() {
}
}
void main(){
king myKing;
const int start = 0;
myKing.calculatebmBc!(start)();
//1. enum bmBcTable = bmBc;
}
The variables bmBc and bmh can't be read at compile time because you define them as regular runtime variables.
You need to define them as enums, or possibly immutable, to read them at compile time, but that also means that you cannot modify them after initialization. You need to refactor your code to return values instead of using out parameters.
Alternatively, you can initialize them at runtime inside of a module constructor.

how to pass a reference to const pointer correctly?

I just wonder how I can efficiently pass a reference to const pointer to an object of a class.
For example,
class BigData
{
public:
int m[1000];
};
void Func(const BigData* const& bigData)
{
// just read bigData; No modification on bigData.
}
int main()
{
BigData* bigData = new BigData();
Func(bigData);
}
Above example, I do not quite understand why I have to put const before reference(&).
If I try to build it without the reference, the compiler complains about
cannot convert parameter 1 from 'BigData *' to 'const BigData *&'
Seems like it is related to R-value rule but I don't know what rule exactly governs this case.
TIA
}
Don't. Just pass the pointer by value. Syntactically it is easier for the called function to use, and will have less overhead.
void Func(const BigData *bigData)

How to use stdext::hash_map?

I would like to see a simple example of how to override stdext::hash_compare properly, in order to define a new hash function and comparison operator for my own user-defined type. I'm using Visual C++ (2008).
This is how you can do it
class MyClass_Hasher {
const size_t bucket_size = 10; // mean bucket size that the container should try not to exceed
const size_t min_buckets = (1 << 10); // minimum number of buckets, power of 2, >0
MyClass_Hasher() {
// should be default-constructible
}
size_t operator()(const MyClass &key) {
size_t hash_value;
// do fancy stuff here with hash_value
// to create the hash value. There's no specific
// requirement on the value.
return hash_value;
}
bool operator()(const MyClass &left, const MyClass &right) {
// this should implement a total ordering on MyClass, that is
// it should return true if "left" precedes "right" in the ordering
}
};
Then, you can just use
stdext::hash_map my_map<MyClass, MyValue, MyClass_Hasher>
Here you go, example from MSDN
I prefer using a non-member function.
The method expained in the Boost documentation article Extending boost::hash for a custom data type seems to work.

Resources