So far I've been using the C# Mersenne Twister found here to generate random numbers:
http://www.centerspace.net/resources.php
I just discovered SFMT which is supposed to be twice as fast here:
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/
Can anyone point me at a C# implementation of SFMT?
My requirements are to generate an integer between (and including) 0 and 2^20 (1048576).
I need to do this trillions of times everyday for a simulation running on a 24 hour clock so I am prepared to spend days tweaking this to perfection.
Currently I've tweaked the Center Space Mersenne Twister by adding a new method to fit my requirements:
public uint Next20()
{
return (uint)(genrand_int32() >> 12);
}
Using the method genrand_int32() I'd like to produce my own version, genrand_int20(), that generates an integer between (and including) 0 and 2^20 to save on the cast above and shift but I don't understand the mathematics. Exactly how can I do this?
Also is using an uint going to be faster that int, or is just a matter of addressable numbers? Because I only need up to 1048576, I am only concerned with speed.
Also this will be running on a Windows Server 2003 R2 SP2 (32bit) box with .NET 2. Processor is AMD Opteron 275 (4 core).
What you can do is download the source from the link you discovered on Code Project. Unzip it, load the solution in Visual Studio and compile it. This will give you source, an unmanaged c dll and a .lib file.
You can P/Invoke the functions in this dll, (there are only 5 simple functions exported, of which you need only two) or you can use this dll, lib, and the SFMT header file to create a managed wrapper dll you can use in C# without P/Invoke. I just tried this method and it was very simple to do. There was no explicit marshalling involved.
Here's how. Once you have downloaded and compiled the source (you need the header and the lib file that is created in addition to the dll) create a new C++ CLR Class Library project. Call it WrapSFMT or something. Go the project properties. Under C++/Precompiled Headers, change to "Not using precompiled headers." Under the Linker/General/Additional Library Directories, enter the path to the SFMT.lib. Under Linker/Input/Additional Dependencies, add SFMT.lib. Close the property pages. Copy SFMT.h to your project folder and include it in the project.
Edit WrapSFMT.h to read as follows:
#pragma once
#include "SFMT.H"
using namespace System;
namespace WrapSFMT {
public ref class SRandom
{
public:SRandom(UInt32);
public:UInt32 Rand32(void);
};
}
These declare the methods that will be in your class. Now edit WrapSFMT.cpp to read:
#include "WrapSFMT.h"
namespace WrapSFMT {
SRandom::SRandom(UInt32 seed)
{
init_gen_rand(seed);
}
UInt32 SRandom::Rand32()
{
return gen_rand32();
}
}
These implement the methods you declared in the header file. All you are doing is calling functions from the SFMT.dll, and C++/CLI is automatically handling the conversion from unmanaged to managed. Now you should be able to build the WrapSFMT.dll and reference it in your C# project. Make sure the SFMT.dll is in the path, and you should have no problems.
You can find a C# implementation of SFMT (plus other RNG algorithms) at...
http://rei.to/random.html
The page and source code comments are in Japanese but you should be able to figure it out.
You can also find a Google-translated version (to English) of the page at...
http://translate.google.com/translate?hl=en&sl=ja&u=http://rei.to/random.html
I don't really see your problem with speed here. On my machine (Core 2 Duo T7200 # 2 GHz) generating a random integer with MT19937 or MT19937-64 takes around 20 ns (on average, when drawing 50000 numbers). So that'd be around 4,32 × 1012 (so around 4 trillion numbers) a day. And that's for one core. With Java. So I think you can expect the performance to be more than adequate for your needs.
To actually answer your question: I don't know of a C# implementation of SFMT, but conversion of the C code to C# should be fairly straightforward. However, you're not gaining much, as SFMT is optimized for SIMD and C# currently doesn't support this directly.
Is there a reason you can't compile the C implementation into a DLL and call this from your C# code?
EDIT:
I'm sorry, but I have only a very limited knowledge of C (and indeed C#), but the "How to create a C dll" may be answered here: http://www.kapilik.com/2007/09/17/how-to-create-a-simple-win32-dll-using-visual-c-2005/ and the how fast can be checked by profiling the code.
Maybe this is what you're looking for?
There is a list of several implementations.
Specifically, this one (by Cory Nelson) might be useful.
Related
I'm migrating an old application in VB6 to C# and I've find a problem with a random number sequence:
(pin is a number greater than 0 in string format)
In my VB code, I've found:
Rnd("-" & pin)
Randomize(CDbl(pin))
So, the code generates the same number sequence all the times (read this note)
Now, in my C# code, I have:
Random r = new Random(int.Parse(pin))
But it does not generate the same sequence.
I'm trying to avoid VBMath.Rnd() instruction, if it's possible.
Please, can you tell me what is the equivalent code in C#?
Thanks a lot in advance!
There are various problems here:
You decided you don't wan't to use Microsoft reimplementation of the Random()/Rnd() VB6 methods (from assembly Microsoft.VisualBasic) and
There is no complete, public documentation of the Random() function (there is a partial documentation of the Rnd() function, minus the part about reseeding using negative numbers here and here)
Now... There is a reimplementation of the algorithm in VB.NET here that claims to be VBMath Rnd() 1:1 Clone,
but the problem is the legality of that gist... We don't know how the author reverse engineered the algorithm... If what you are doing is for private use, you clearly can use IlSpy and take a look at the Microsoft.VisualBasic assembly where you can find the whole algorithm (it is less than 100 lines of code, and projectData.m_rndSeed is 327680 as documented on the wiki). If you want, you don't even need to use IlSpy... Microsoft put the source code (written in vb.net) in its referencesource github, but note that the same legality problems apply: the code under referencesource is for browsing only.
if I wish to marshal an int in C# (Int32) to/from a native (C++) library, what's the best way to declare the relevant variable in C++ code?
I could use a standard int but I'd rather be explicit about the width of that variable (I know that it's 32-bit on most platforms anyway).
So far, I can see two options:
int32_t in <cstdint>
__int32 (MSVC++ identifier) ... However I'd like to remain platform independent if I can
I seem to recall hearing that C++11 has some new library for this, but I can't seem to find any mention of it.
Thank you.
The int keyword in the currently shipping C# and C++ compilers are type aliases, respectively for System.Int32 and __int32, the concrete types used by their back-ends. I've been writing code for 30 years and have used 8-bit, 16-bit, 32-bit and 64-bit processors. And used int 30 years ago like I do today. And expended very little effort to port programs to the next generation architecture or operating system version.
You see this back in the winapi as well. Every type used for a function argument or return value is a type alias. The CreateWindow() function in Windows version 1.0 looks exactly the same as the one you use in the 64-bit version of Windows 8.1
I have no illusion that this progression suddenly stopped today. 128-bit processors are already the bread-and-butter for IBM. Languages use type aliases to prevent themselves from becoming rapidly outdated and forgotten. True for languages like C and C++, true for C# as well. Although it certainly is going to require moving a bigger rock in the case of C#, the identity is engraved in most any C# programmer's mind right now.
Intentionally not using type aliases makes your program less portable.
You can use int32_t which is exactly 32 bits. It is possible for there to be a C++ implementation for which int32_t is not defined, but in that case, all bets are off.
On every platform that I know of which supports C#, then C/C++ int is 32 bits and so you may be over-thinking this.
Another thing to consider is what type your C++ code accepts. If it accepts int, and you use a platform where int is not 32 bits, then you still have a problem.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
Could someone please help me to convert C# to C++? here is an example:
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading;
namespace read_website
{
class Program
{
static void Main(string[] args)
{
while (true)
{
DownloadString("http://www.xxx.asp");
Thread.Sleep(100);//update every 100 millisecoand
}
}
public static void DownloadString(string address)
{
WebClient client = new WebClient();
string website = client.DownloadString(address);
get_Current_X1_value(website);
}
static void get_Current_X1_value(string web)
{
int x = web.IndexOf("Current X1 value:");
string part1 = web.Substring(x, 100);
string[] array = part1.Split('>', '<');
for (int i = 0; i < array.Length; i++)
{
if (array[i].Contains("Current X1 value:"))
Console.Write(array[i]);
if (array[i].Contains("W"))
Console.WriteLine(array[i]);
}
}
}
}
Actually as it is complicated to mix C# and C++ on unix, I am trying to convert C# to C++
Actually as it is complicated to mix C# and C++ on unix, I am trying to convert C# to C++
Have you considered Mono? It is something that's definitely worth checking before starting to learn C++ in order convert and run an existing .NET application on Unix. It's also binary compatible meaning that you don't even need to recompile your existing assembly.
Learn C#, learn C++, and spend a lot of time rewriting.
Or use PInvoke from the C# assembly to call into a C++ dll.
Or write managed C++ and compile with the /clr switch. The resulting assembly can be referenced and used from C# projects.
It is nearly impossible to directly translate C# to C++ so that it will run on Unix machines.
This is mainly due to the fact that the .NET Framework is not available (from C++) on Unix machines. Mono will allow you to run many C#/.NET programs, but does not support C++/CLI (the C++ extensions that allow directly working with the .NET Framework).
Converting the language is possible - though difficult due to differences in approach (e.g., garbage collection in C#), but the framework calls will require porting to different libraries, and it is often not a good candidate for a direct translation.
For example, in your code above, you'd have to decide on a C++ library for web access - and once you had that choice made, it would dictate the code required to call into that library to download the website string.
I'm using C# to C++ converter time to time. It's really great for snippet conversion from c# to c++ or c++/cli.
Consider looking at Vala. Vala is a C#-like language that converts into C and then into an executable. There are very little differences with C#. You will still have to use your brain though.
You may want to consider CoreRT. It's a .NET project whose goal is to eliminate the need for the CLR to be present on the target platform for running an application. Instead, it generates C++ code from a given C# code. That C++ code is compiled and linked on any target platform that supports C++.
A post on a Microsoft blog said: "If I really want to write some C# code and have it 'just work' on a new IoT device, I don’t have any options until the RyuJIT is capable of generating machine code that works with that processor and operating system." By cross-compiling C# to C++, .Net developers can then deliver their applications without needing to wait for .Net to be deployed on a given platform.
https://github.com/dotnet/corert
Edit:
The site listed has been discontinued. I'll leave the old answer here for reference ...
Old answer:
Here is an online converter that will automate the process for you! ...
Varycode online converter
It can do C# to C++ and back again as well as converters for Ruby, Python, Java & VB, apparently!
Edit:
It appears to have had its C++ (and java) functionality removed - it says temporarily, but has done so for a long time now. Hopefully they'll resurrect it soon!
Still works for some other languages (VB, Ruby, Python, Boo).
As already mentioned here, the translation of libraries can be an issue, but one open source project that might help at some cases is:
http://alexalbala.github.io/Alter-Native/
Citation from its main page:
It provides a tool to easy port applications
from high-level languages such as .NET to
native languages like C++. It is a research project
and it is under development with the
collaboration of UPC - BarcelonaTech and AlterAid S.L.
Alright so I have this C++ image capturing class. I was wondering if I could get some help..I know basic C++ (I have done one intro to c and one intro to c++ class) and I have NO idea how to do this:
I need to use this class (ie create a new c++ project in my solution) and use c# to reference it and use it to save a screenshot of the screen.
When I try to add a new project I dont know which one to choose (win32, mfc, atl, clr, abc, xyz, and so on) .
The image capturing class is here:
http://pastebin.com/m72414ab
I don't know if I need to create .h files or just a .cpp file would do.. like honestly I have no clue where to start lol. I am looking for a solution, but i want to learn in the process so I dont have to ask next time (not to mention that I like c++ so I am gonna continue coding with it)
You cannot easily use C++ classes from C# without knowing some somewhat specialized information about C++/CLI - either rewrite your C++ class in C and use P/Invoke, or find a fully C# solution.
But I'd like to use this c++ class for speed and memory.
I question this, unless you are capturing images thousands of times a second, there's no way choosing C++ would be of any benefit, and it makes your program much more complicated. Stick with C# until you know you need the slight performance boost.
.NET version 2.0 and above include a CopyFromScreen method on the Graphics object. You can create an image, obtain a drawing surface (Graphics) for that, and then copy from the screen into the image.
A quick bit of Googling produced a simple tutorial which demonstrates this using Visual Basic .NET, although it's trivial to port to C#.
This solution results in the same GDI+ calls that your C++ version uses, with the benefit of not having to link in external C++ code (which, as mentioned above, is not straightforward).
It is definitely possible to use C++ constructs from C#, but it does require some dirty tricks. If I remember correctly, last time I tried to do this I used a Managed C++ layer between C++ and C#, and I think this is the most common way to do it. This method worked well, but indeed was unnecessarily complicated.
I've recently been wrestling with an algorithm which was badly implemented (i.e. the developer was pulled off onto another project and failed to adequately document what he'd done) in C#.
I've found an alternative (from numerical recipes) which works but is written in C++. So I'm thinking probably the safest way to get something working would be to wrap the C++ up in a DLL.
Bearing in mind that I'm still a bit green when it comes to C# and have never tried making a DLL from scratch, does this sound like a reasonable approach (and if so, has anyone tried this / got any advice)? Or should I go the whole hog and try and port the C++ routine into C#?
Edit - I'm not looking for anyone to make the decision for me, but if anyone has any exprience of either route I'd be interested to hear their opinions and any nasty pitfalls that should be avoided. For example, how nasty is passing in lists of data from C# to a C++ STL vector?
I tried linking to c-dll's from c# code with quite good results, even though I had some problems sending data between the environments. Otherwise the procedure is quite straight forward. The more data you send back and forth (both amount and frequency) the slower your program will run, but you have probably already figured this out on your own.
The main drawback was maintaining the c#-c glue code (interface code) each time something changed or someone found a bug.
Here is a bit of code to get you started:
using System.Runtime.InteropServices;
class myDllCaller {
//call to function in the dll returning an int
[DllImport("MyFavorite.dll")]
private static extern int dllFunction(//list of parameters to function);
public static void Main() {
int rerult = dllFunction();
}
}
If the C# version Mitch references isn't of a suitable licence for your purposes, You could use a managed C++ wrapper, that could reuse, and wrap the C code you have, but still be visible to your managed applications as a native .Net assembly. I've used this approach in the past for using the C API of a library that didn't have its own native .Net API, and found it relatively painless marshalling data between the two.
It depends what your goals are.
If it's to have a working application I'd weigh-up the costs and benefits of both approaches and go with the most cost effective.
If it's to improve your C# then by all means rewrite the C.
...Or you could download the already implemented code in C# from here.