#include "stdafx.h"
ref class station{
public:
station(){
};
void wrapper_1()
{
this->somefunct(); /*happy*/
};
void wrapper_2()
{
this->station(); /*not happy*/
};
void somefunct(){
System::Console::WriteLine(L"abcde");
};
};
int main(array<System::String^>^ args)
{
station^ temp_1 = gcnew station();
temp_1->wrapper_1();
System::Console::ReadLine();
};
I want to use the this pointer to call my constructor within my station class, it doesn't like this and throws the following error:
error C2273: 'function-style cast' : illegal as right side of '->'
operator.
Can someone explain to me how the constructor differs to other functions when using the pointer this to point to the function. I don't want to take the easy way out using station::station();
example of what I meant to #hans-passant
#include "stdafx.h"
ref class station{
public:
station(int par_1,int par_2)
{
int sum = par_1 + par_2;
System::Console::WriteLine(System::Convert::ToString(sum));
//default value output 13
};
station(){
int pass_1 = 5;
int pass_2 = 8;
station(pass_1,pass_2); /* But why couldn't I use this->station(pass_1,pass_2);*/
};
};
int main(array<System::String^>^ args)
{
station^ obj = gcnew station();
System::Console::ReadLine();
};
Related
This works...
struct FOO
{
char bar1[50 + 1];
char bar2[50 + 1];
};
FOO foo[] =
{
{"baz1", "baz2"},
{"baz3", "baz4"}
};
But this does not...
struct FOO2
{
FOO2(void) { };
char bar1[50 + 1];
char bar2[50 + 1];
};
FOO2 foo2[] =
{
{"baz1", "baz2"},
{"baz3", "baz4"}
};
Morover, this...
struct FOO3
{
void init(void) { };
char bar1[50 + 1];
char bar2[50 + 1];
};
FOO3 foo3[] =
{
{"baz1", "baz2"},
{"baz3", "baz4"}
};
...works too.
So, methods don't disallow array initialization but a constructor does.
From Microsoft's error description these attributes (among others) cause an entity to become a "non-aggregate" and therefore no longer a valid target for array initialization:
Constructors
Private or protected members
Base classes
Virtual functions
Why, in the case of constructors?
I am trying to change the message for bad_alloc.
#include <iostream>
#include <iomanip>
#include <stdexcept>
using std::logic_error;
using std::bad_alloc;
class OutOfRange : public logic_error {
public:
OutOfRange(): logic_error("Bad pointer") {}
};
class OutOfMem : public bad_alloc {
public:
OutOfMem(): bad_alloc("not enough memory") {}
};
OutOfRange() works fine, but OutOfMem sends me an error:
No matching function for call to std::bad_alloc::bad_alloc(const char[21])
The compile error is telling you that that bad_alloc constructor does not take a char *.
e.g. See here
Instead, note that exception what method is vritual and use that instead.
class OutOfMem : public bad_alloc {
public:
OutOfMem() {}
const char *what() const {
return "not enough memory";
}
};
Edit: note you might have to state it doesn't throw as follows:
//... as before
virtual const char * what() const throw () {
return "not enough memory";
}
// as before ...
I wrote QSQLTableModel inheritor for working with qml and it's work well. I need use it with QTableView too, data shows, but I cannot modify it - when I edit everything is ok, but all changes drop when I get out from field (I know about editStrategy, but the problem occurs earlier). I suppose that something wrong with virtual function, but I cant undestant what. If i create QSqlTableModel with the same parameters, everything is ok. Somebody have any idea how can i fix this? My code:
h:
class ListModel : public QSqlTableModel
{
Q_OBJECT
Q_PROPERTY( int count READ rowCount() NOTIFY countChanged())
signals:
void countChanged();
public:
Q_INVOKABLE QVariant data(const QModelIndex &index, int role) const;
ListModel(QObject *parent, QSqlDatabase _db):QSqlTableModel(parent,_db){this->setEditStrategy(QSqlTableModel::OnManualSubmit);}
void applyRoles();
#ifdef HAVE_QT5
virtual QHash<int, QByteArray> roleNames() const{return roles;}
#endif
private:
int count;
QHash<int, QByteArray> roles;
};
cpp:
//based on http://qt-project.org/wiki/How_to_use_a_QSqlQueryModel_in_QML
void ListModel::applyRoles()
{
roles.clear();
qDebug()<<"\n"<<this->tableName();
for (int i = 0; i < this->columnCount(); i++) {
QString role=this->headerData(i, Qt::Horizontal).toString();
roles[Qt::UserRole + i + 1] = QVariant(role).toByteArray();
qDebug()<<this->headerData(i, Qt::Horizontal);
}
#ifndef HAVE_QT5
setRoleNames(roles);
#endif
}
QVariant ListModel::data(const QModelIndex &index, int role) const{
QVariant value;
if(role < Qt::UserRole)
{
value = QSqlQueryModel::data(index, role);
}
else {
int columnIdx = role - Qt::UserRole - 1;
QModelIndex modelIndex = this->index(index.row(), columnIdx);
value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
}
return value;
}
UPD
I understood that the problem is in data method's quantifier const, if I remove it everything is ok with QTableView, but I cant get data from model with gml's listviews. I see only one solution - replace interition from QSqlTableModel with aggregation it, but maybe someone knows better solution?
Summary: Solved with strange hack - inherited from QSqlRelationalTableModel instead QSqlTableModel, I think the reason is that QSqlRelationalTableModel has rewritten non virtual method data
I have a third-party C library that provides this header:
//CLibrary.h
#include <Windows.h>
#include <process.h>
typedef void (WINAPI *CLibEventCallback)(int event, void *data);
__declspec(dllexport) bool CLibStart (CLibEventCallback callback, void *data);
// CLibrary.c -- sample implementation
static CLibEventCallback cb;
void _cdecl DoWork (void *ptr)
{
for (int i = 0; i < 10; ++i)
{
cb (i*i, ptr);
Sleep (500);
}
}
__declspec(dllexport) bool CLibStart (CLibEventCallback callback, void *data)
{
cb = callback; // save address for DoWork thread...
_beginthread (DoWork, 0, data);
return true;
}
I need to create a C++/CLI class that can call CLibStart and provide a class method as the function pointer. As suggested below, this needs to be done with GetFunctionPointerForDelegate. Because the delete constructor includes 'this' and doesn't require a static method, I don't need to pass 'this' into CLibStart.
using namespace System;
using namespace System::Runtime::InteropServices;
namespace Sample {
public ref class ManagedClass
{
delegate void CLibraryDelegate (int event, void *data);
private:
CLibraryDelegate^ managedDelegate;
IntPtr unmanagedDelegatePtr;
int someInstanceData;
public:
ManagedClass()
{
this->managedDelegate = gcnew CLibraryDelegate(this, &ManagedClass::ManagedCallback);
this->unmanagedDelegatePtr = Marshal::GetFunctionPointerForDelegate(this->managedDelegate);
this->someInstanceData = 42;
}
void Start ()
{
// since the delegate includes an implicit 'this' (as static function is not needed)
// I no longer need to pass 'this' in the second parameter!
CLibStart ((CLibEventCallback) (void *) unmanagedDelegatePtr, nullptr);
}
private:
void Log (String^ msg)
{
Console::WriteLine (String::Format ("someInstanceData: {0}, message: {1}", this->someInstanceData, msg));
}
void ManagedCallback (int eventType, void *data)
{
// no longer need "data" to contain 'this'
this->Log (String::Format ("Received Event {0}", eventType));
}
};
}
All of this compiles and runs fine using this C# tester:
using System;
using Sample;
namespace Tester
{
class Program
{
static void Main(string[] args)
{
var mc = new ManagedClass();
mc.Start();
Console.ReadKey();
}
}
}
Sample output:
Received Event 0
Received Event 1
Received Event 4
Received Event 9
Received Event 16
Received Event 25
Received Event 36
Received Event 49
Received Event 64
Received Event 81
Outstanding questions:
I have this feeling that I need to use gcroot and/or pin_ptr? If
so, how? where?
Thanks.
gcroot should be in place where ref class stores delegate, like:
gcroot<CLibraryDelegate^> managedDelegate;
I have a trouble working with JCUDA. I have a task to make 1D FFT using CUFFT library, but the result should be multiply on 2. So I decided to make 1D FFT with type CUFFT_R2C. Class responsible for this going next:
public class FFTTransformer {
private Pointer inputDataPointer;
private Pointer outputDataPointer;
private int fftType;
private float[] inputData;
private float[] outputData;
private int batchSize = 1;
public FFTTransformer (int type, float[] inputData) {
this.fftType = type;
this.inputData = inputData;
inputDataPointer = new CUdeviceptr();
JCuda.cudaMalloc(inputDataPointer, inputData.length * Sizeof.FLOAT);
JCuda.cudaMemcpy(inputDataPointer, Pointer.to(inputData),
inputData.length * Sizeof.FLOAT, cudaMemcpyKind.cudaMemcpyHostToDevice);
outputDataPointer = new CUdeviceptr();
JCuda.cudaMalloc(outputDataPointer, (inputData.length + 2) * Sizeof.FLOAT);
}
public Pointer getInputDataPointer() {
return inputDataPointer;
}
public Pointer getOutputDataPointer() {
return outputDataPointer;
}
public int getFftType() {
return fftType;
}
public void setFftType(int fftType) {
this.fftType = fftType;
}
public float[] getInputData() {
return inputData;
}
public int getBatchSize() {
return batchSize;
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
public float[] getOutputData() {
return outputData;
}
private void R2CTransform() {
cufftHandle plan = new cufftHandle();
JCufft.cufftPlan1d(plan, inputData.length, cufftType.CUFFT_R2C, batchSize);
JCufft.cufftExecR2C(plan, inputDataPointer, outputDataPointer);
JCufft.cufftDestroy(plan);
}
private void C2CTransform(){
cufftHandle plan = new cufftHandle();
JCufft.cufftPlan1d(plan, inputData.length, cufftType.CUFFT_C2C, batchSize);
JCufft.cufftExecC2C(plan, inputDataPointer, outputDataPointer, fftType);
JCufft.cufftDestroy(plan);
}
public void transform(){
if (fftType == JCufft.CUFFT_FORWARD) {
R2CTransform();
} else {
C2CTransform();
}
}
public float[] getFFTResult() {
outputData = new float[inputData.length + 2];
JCuda.cudaMemcpy(Pointer.to(outputData), outputDataPointer,
outputData.length * Sizeof.FLOAT, cudaMemcpyKind.cudaMemcpyDeviceToHost);
return outputData;
}
public void releaseGPUResources(){
JCuda.cudaFree(inputDataPointer);
JCuda.cudaFree(outputDataPointer);
}
public static void main(String... args) {
float[] inputData = new float[65536];
for(int i = 0; i < inputData.length; i++) {
inputData[i] = (float) Math.sin(i);
}
FFTTransformer transformer = new FFTTransformer(JCufft.CUFFT_FORWARD, inputData);
transformer.transform();
float[] result = transformer.getFFTResult();
HilbertSpectrumTicksKernelInvoker.multiplyOn2(transformer.getOutputDataPointer(), inputData.length+2);
transformer.releaseGPUResources();
}
}
Method which responsible for multiplying uses cuda kernel function.
Java method code:
public static void multiplyOn2(Pointer inputDataPointer, int dataSize){
// Enable exceptions and omit all subsequent error checks
JCudaDriver.setExceptionsEnabled(true);
// Create the PTX file by calling the NVCC
String ptxFileName = null;
try {
ptxFileName = FileService.preparePtxFile("resources\\HilbertSpectrumTicksKernel.cu");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Initialize the driver and create a context for the first device.
cuInit(0);
CUdevice device = new CUdevice();
cuDeviceGet(device, 0);
CUcontext context = new CUcontext();
cuCtxCreate(context, 0, device);
// Load the ptx file.
CUmodule module = new CUmodule();
cuModuleLoad(module, ptxFileName);
// Obtain a function pointer to the "add" function.
CUfunction function = new CUfunction();
cuModuleGetFunction(function, module, "calcSpectrumSamples");
// Set up the kernel parameters: A pointer to an array
// of pointers which point to the actual values.
int N = (dataSize + 1) / 2 + 1;
int pair = (dataSize + 1) % 2 > 0 ? 1 : -1;
Pointer kernelParameters = Pointer.to(Pointer.to(inputDataPointer),
Pointer.to(new int[] { dataSize }),
Pointer.to(new int[] { N }), Pointer.to(new int[] { pair }));
// Call the kernel function.
int blockSizeX = 128;
int gridSizeX = (int) Math.ceil((double) dataSize / blockSizeX);
cuLaunchKernel(function, gridSizeX, 1, 1, // Grid dimension
blockSizeX, 1, 1, // Block dimension
0, null, // Shared memory size and stream
kernelParameters, null // Kernel- and extra parameters
);
cuCtxSynchronize();
// Allocate host output memory and copy the device output
// to the host.
float freq[] = new float[dataSize];
cuMemcpyDtoH(Pointer.to(freq), (CUdeviceptr)inputDataPointer, dataSize
* Sizeof.FLOAT);
And the kernel function is next:
extern "C"
__global__ void calcSpectrumSamples(float* complexData, int dataSize, int N, int pair) {
int i = threadIdx.x + blockIdx.x * blockDim.x;
if(i >= dataSize) return;
complexData[i] = complexData[i] * 2;
}
But when I'm trying to pass the pointer which points to the result of FFT (in device memory) to the multiplyOn2 method, it throws the exception on cuCtxSynchronize() call. Exception:
Exception in thread "main" jcuda.CudaException: CUDA_ERROR_UNKNOWN
at jcuda.driver.JCudaDriver.checkResult(JCudaDriver.java:263)
at jcuda.driver.JCudaDriver.cuCtxSynchronize(JCudaDriver.java:1709)
at com.ifntung.cufft.HilbertSpectrumTicksKernelInvoker.multiplyOn2(HilbertSpectrumTicksKernelInvoker.java:73)
at com.ifntung.cufft.FFTTransformer.main(FFTTransformer.java:123)
I was trying to do the same using Visual Studion C++ and there no problems with this. Could you please help me.
P.S.
I can solve this prolem, but I need to copy data from device memory to host memory and then copy back with creating new pointers every time before calling new cuda functions, which slows my program executing.
Where exactly does the error occurs at which line?
The Cuda error can also be a previous error.
Why do you use Pointer.to(inputDataPointer), you already have that device pointer. Now you pass a pointer to the device pointer to the device?
Pointer kernelParameters = Pointer.to(Pointer.to(inputDataPointer),
I also recommend to use "this" qualifier or any other marking to detect instance variables. I hate and refuse to look through code, especially as nested and long as your example if I cannot see which scope the variable in methods have trying to debug it by just reading it.
I don't wanna ask myself always where the hell comes this variable from.
If a complex code in a question at SO is not formatted properly I don't read it.