• Advertisement
Sign in to follow this  

Unity Passing on variable number of arguments...again

This topic is 4435 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I know a simular problem has already been discussed here but those answers only aplied when passing to libraryfunctions. What if I want to pass on the arguments to one of my own functions? Heres what I meen:

//This one formats the output and returnes the string
char* MyFormatFunction(char *input, ...) {
  va_list valist;
  va_start(valist,input);

  int length=512; //should be enough, havn't come up with a better solution
  char* str=(char*) malloc(length);
  vsnprintf(str,512,input,valist);
  va_end(valist);
  return str;
  };

char* MyPreProcessorFunction(char* input, ...) {
  //
  //I do some stuff with the input string here
  //
  
  char* str=MyFormatFunction(input, ...) // <- how do I pass on the arguments?
  return str;
  };

I know I could make MyFormatFunction take a va_list as the second argument but then I wouldnt be able to call it directly in ordinary printf style. You might also wonder why on earth I would declare a new function like MyFormatFunction when what it does basicly can be sumerized in just two lines of code (malloc and vsnprintf). To tell you the truth I cant remember right now :P. But I know it was necessery. One reason I can think of now is that I wanted to wrap all my output functions with a nice prefix and I wanted MyFormatFunction to be a part of that group. Thanks in advance for any replies. /ThunderSky

Share this post


Link to post
Share on other sites
Advertisement
You need to break MyFormatFunction into two functions, just like printf/vprintf and similar library functions. Then, have the variadic version call the one that takes a va_list parameter.

Hard-coded buffer sizes = evil.

Share this post


Link to post
Share on other sites
Returning new'd string buffers like that is IMO evil as well, unless you have a clear understanding of who owns the string and therefor who is responsible for cleaning it up, or if you return a smart pointer to the buffer.

Share this post


Link to post
Share on other sites
Quote:

You need to break MyFormatFunction into two functions, just like printf/vprintf and similar library functions. Then, have the variadic version call the one that takes a va_list parameter.

Thanks Fruny, quite simple, this shows that I still have a lot to learn...

Quote:

Hard-coded buffer sizes = evil.

I dont like that "should be enough", and whats even wors is that I have no error checking yet either. But as I understand it the implementations of sprintf and related functions seldom comply with the standard so I cant really be sure if will return the buffersize needed if an error occurs.

I read that there is a specific function that doesnt acctually return the formatted buffer, but the size that would be needed to store it. Unfortunatly, it seems to be IDE dependent. I got hold of the VC version on microsofts developer pages but Im using DevC++ (MinGW) so that didnt help much. I later found that there is a g++ version (MinGW is a g++ compiler right?). But when I tried to compile whith the g++ version DevC++ said it was undeclared so...Im cinda lost. If you know how to solv the problem, great! otherwise I think Ill just leav it. Not verry nice, but it'l be enough for what Im using it for.

Quote:

Returning new'd string buffers like that is IMO evil as well, unless you have a clear understanding of who owns the string and therefor who is responsible for cleaning it up, or if you return a smart pointer to the buffer.


yeah I know..guess Im just an evil cinda guy...(whats a smart pointer?)


Edit. Forgot the thank you guys for the comments so..thanks

Share this post


Link to post
Share on other sites
Quote:
Original post by Thunder Sky
I got hold of the VC version on microsofts developer pages but Im using DevC++ (MinGW) so that didnt help much. I later found that there is a g++ version (MinGW is a g++ compiler right?).



Since you're already using C++, you could use boost::format.

Share this post


Link to post
Share on other sites
Quote:
Original post by Fruny
Since you're already using C++, you could use boost::format.


Seconded. boost::format is nice and powerful and type safe and all that.

A smart pointer is a class that basically deletes an object when the last reference to it is destroyed. In your code above you return a malloc'd char buffer. If you returned


boost::shared_array<char> MyFunction()
{
boost::shared_array<char> mysmartbuffer(new char[length]);
}
// do stuff
return mysmartbuffer;


This would return a 'smart pointer' to this memory block. When the last smart pointer that references that block goes out of scope or is otherwise delted, the buffer will be deleted automatically, resulting in no memory leak and no need to worry about if the block gets deleted properly or not.

Share this post


Link to post
Share on other sites
Quote:

Since you're already using C++


Well I guess I do, but I have no idea (well some idea) of how to use classes and a lot of the other C++ stuff. Havnt got the time or strength to read up on the subject... so I tend to stick to the more basic C. for now.

besides, Im using this for a small chat program so I prefer not to use any nonstandard libraries.

Share this post


Link to post
Share on other sites
Which brings me to another thing Ive been meaning to ask about. If I include a file, say string.h, how much does the final executable grow in size. would it be better to do a
for(i=0;buffer!='\0';i++);
instead of including the whole string.h file and using strlength?

Mainly Im asking because windows.h is huge when you count in all the other files it inculdes and I like to use Sleep() in my simpler console apps and I read somewhere that that could be acheaved some other way.

thanks for the other replies

Share this post


Link to post
Share on other sites
Smart compilers don't leave un-used code in the final executable. The actual code for the functions you don't use should not end up in the .exe. It may increase compile time a bit though, but not enough to worry about whether you should use external stuff.

Share this post


Link to post
Share on other sites
Quote:
Original post by Thunder Sky
Well I guess I do, but I have no idea (well some idea) of how to use classes and a lot of the other C++ stuff.


To a large extent, using existing classes should be easier than writing classes. Especially with well-designed libraries.

Quote:
Havnt got the time or strength to read up on the subject... so I tend to stick to the more basic C. for now.

Quote:
Thanks Fruny, quite simple, this shows that I still have a lot to learn...


Do you want to learn or not? [smile] The best way to learn is to actually start using the libraries. You'll probably quickly make up for the "lost" time.

Quote:
besides, Im using this for a small chat program so I prefer not to use any nonstandard libraries.


The C standard library does not include any networking facilities, so you're going to need non-standard libraries anyway. Additionally, quite a few components from the Boost library have been accepted into the upcoming revision of the C++ standard library. You're on shaky grounds to use non-standardization as an argument for rejection. [smile]

Quote:
and I like to use Sleep() in my simpler console apps


Sleep() isn't a standard C function either. [wink]

Quote:
(whats a smart pointer?)


A smart pointer is an object designed to act like a pointer syntactically, but with additional functionality, such as keeping track of the number of references to the block it points to, and automatically releasing the block when that reference count falls to zero.

Share this post


Link to post
Share on other sites
haha yeah just realized the things you pointed out to me Fruny

Quote:

A smart pointer is an object designed to act like a pointer syntactically, but with additional functionality, such as keeping track of the number of references to the block it points to, and automatically releasing the block when that reference count falls to zero.


A bit of topic but.. how is that possible? does it use some cind of preprocessing to check where the code reference to the block?
btw, if the answer is complicated, dont bother, I dont have I wide enought understanding of C to get the more complicated stuff

anyways thanks for the fast help you guys provided

Share this post


Link to post
Share on other sites
Quote:
Original post by Thunder Sky
A bit of topic but.. how is that possible? does it use some cind of preprocessing to check where the code reference to the block?


A smart pointer is not a pointer per-se, but an object. Or, if you prefer, in C terms, it's like a struct. You won't be able to pass a smart pointer where a "raw" ("naked", "dumb", "C") pointer is expected.

In C++, you can do operator overloading. Which means that you can write foo+bar even for custom types. Overloading also extends to those operators that are required to mimic a pointer:

struct foo { int x; };

class noisy_foo_pointer
{
private:
foo* ptr;
public:
noisy_int_pointer(foo* p) : ptr(p) {}
foo& operator*() const { puts("Derefenced!"); return *ptr; }
foo* operator->() const { puts("Accessed!"); return ptr; }
};


Assuming p is a valid noisy_foo_pointer, writing *p or (*p).x will cause "Dereferenced" to be printed, while writing p->x will cause "Accessed" to be printed. Note that since I haven't provided the appropriate operators, you can't do pointer arithmetic on a noisy_foo_pointer.

Now, C++ also allows your types to have constructors (noisy_foo_pointer does have one) and destructors which are called when a variable is created or destroyed. Along with control of the assignment operator, this is pretty much all you need to keep track of the number of smart pointers that reference a given address -- assuming you don't try to cheat and keep dumb pointers around.

When a smart pointer is created from a dumb pointer, set the reference count to 1.
When a smart pointer is created from another smart pointer, increment the reference count -- the same counter will be shared between the two pointers.
When a smart pointer is assigned to another smart pointer, decrement the reference count of the assignment target and increment the count of the source.
When a smart pointer is destroyed, decrement the reference count.
Whenever you decrement that count, check if it reached zero. If it has, release the memory (and destroy the objects that it contained).

Finally, C++ has templates, which allow you to define your smart pointer just once and have it function (safely) for various types, instead of having to write one for ints, one for foos ... void* is rarely needed:

template<typename T>
class noisy_pointer
{
private:
T* ptr;
public:
noisy_pointer(T* p) : ptr(p) {}
T& operator*() const { puts("Derefenced!"); return *ptr; }
T* operator->() const { puts("Accessed!"); return ptr; }
};

typedef noisy_pointer<Foo> noisy_foo_pointer; // to emulate the previous example


Now you can use noisy_pointer<Foo>, noisy_pointer<int>, noisy_pointer<double> ...

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By Innoc uous
      I'm working on a space game, and I suck at art. I would love to get some help from someone who is more skilled than me. Things I need include modular space ship parts and GUI elements. Nothing too fancy, just functional so I can get a prototype put together. This could potentially become a serious project, but for now this is just a hobby project.
       
      In this video, you can see a few things I already completed
      :2018-02-24 20-08-13.flv2018-02-24 20-08-13.flv
    • By Innoc uous
      If you want to incorporate noise into your shaders, the Turbulance Library has you covered. Using code I gathered from this library, I made a cginc file that contains all you need to easily implement noise into your unity shaders. Who knows how this stuff works, but man, does it work well!
       
      https://pastebin.com/LLCUpJut
       
      Here is an example of what you can create using these noise functions.
       
    • By Nio Martinez
      I'll be buying a new laptop as my workstation for building games, Mostly 3D but not hard core. 
       
      I'm stuck at choosing between these 2 specs below. Does this really matter and if so, can some one tell my how and why it matters. 
      Choice1:
      Intel core i5-8250U (8th gen Kabylake refresh)(6 MB Smart Cache, 1.6 GHz Base with Turbo Boost up to 3.4 GHz) 4 cores 8 threads
      RAM 8 GB DDR4 (2400 MHz)
      GPU 2 GB DDR5 Nvidia MX150 256 bit
      SSD: yes
      Choice2:
      Intel core i7-7500U 2.70GHz Base Processor (4M Cache, up to 3.50 GHz Boost) 2 Cores, 4 Threads
      RAM 4 GB DDR4 (1800 MHz)
      GPU 2 GB DDR5 Nvidia GeForce 940MX 256 bit
      SSD: No
       
    • By Manuel Berger
      Hello fellow devs!
      Once again I started working on an 2D adventure game and right now I'm doing the character-movement/animation. I'm not a big math guy and I was happy about my solution, but soon I realized that it's flawed.
      My player has 5 walking-animations, mirrored for the left side: up, upright, right, downright, down. With the atan2 function I get the angle between player and destination. To get an index from 0 to 4, I divide PI by 5 and see how many times it goes into the player-destination angle.

      In Pseudo-Code:
      angle = atan2(destination.x - player.x, destination.y - player.y) //swapped y and x to get mirrored angle around the y axis
      index = (int) (angle / (PI / 5));
      PlayAnimation(index); //0 = up, 1 = up_right, 2 = right, 3 = down_right, 4 = down

      Besides the fact that when angle is equal to PI it produces an index of 5, this works like a charm. Or at least I thought so at first. When I tested it, I realized that the up and down animation is playing more often than the others, which is pretty logical, since they have double the angle.

      What I'm trying to achieve is something like this, but with equal angles, so that up and down has the same range as all other directions.

      I can't get my head around it. Any suggestions? Is the whole approach doomed?

      Thank you in advance for any input!
       
    • By devbyskc
      Hi Everyone,
      Like most here, I'm a newbie but have been dabbling with game development for a few years. I am currently working full-time overseas and learning the craft in my spare time. It's been a long but highly rewarding adventure. Much of my time has been spent working through tutorials. In all of them, as well as my own attempts at development, I used the audio files supplied by the tutorial author, or obtained from one of the numerous sites online. I am working solo, and will be for a while, so I don't want to get too wrapped up with any one skill set. Regarding audio, the files I've found and used are good for what I was doing at the time. However I would now like to try my hand at customizing the audio more. My game engine of choice is Unity and it has an audio mixer built in that I have experimented with following their tutorials. I have obtained a great book called Game Audio Development with Unity 5.x that I am working through. Half way through the book it introduces using FMOD to supplement the Unity Audio Mixer. Later in the book, the author introduces Reaper (a very popular DAW) as an external program to compose and mix music to be integrated with Unity. I did some research on DAWs and quickly became overwhelmed. Much of what I found was geared toward professional sound engineers and sound designers. I am in no way trying or even thinking about getting to that level. All I want to be able to do is take a music file, and tweak it some to get the sound I want for my game. I've played with Audacity as well, but it didn't seem to fit the bill. So that is why I am looking at a better quality DAW. Since being solo, I am also under a budget contraint. So of all the DAW software out there, I am considering Reaper or Presonus Studio One due to their pricing. My question is, is investing the time to learn about using a DAW to tweak a sound file worth it? Are there any solo developers currently using a DAW as part of their overall workflow? If so, which one? I've also come across Fabric which is a Unity plug-in that enhances the built-in audio mixer. Would that be a better alternative?
      I know this is long, and maybe I haven't communicated well in trying to be brief. But any advice from the gurus/vets would be greatly appreciated. I've leaned so much and had a lot of fun in the process. BTW, I am also a senior citizen (I cut my programming teeth back using punch cards and Structured Basic when it first came out). If anyone needs more clarification of what I am trying to accomplish please let me know.  Thanks in advance for any assistance/advice.
  • Advertisement