The DLL was successfully built but it is not working - c++

I use the example Plugin.cpp from amibroker ADK. I make a directory 'ASCII' under the folder 'amibroker' and put all the data inside named *.AQI. But no data found in amibroker. Is there something I changed in function GetQuotesEx cause the problem?
PLUGINAPI int GetQuotesEx( LPCTSTR pszTicker, int nPeriodicity, int nLastValid, int nSize, struct Quotation *pQuotes, GQEContext *pContext )
{
char filename[256];
FILE* fh;
int iLines = 0;
// format path to the file (we are using relative path)
sprintf_s(filename, "ASCII\\%s.AQI", pszTicker);
// open file for reading
fopen_s(&fh, filename, "r");
// if file is successfully opened read it and fill quotation array
if (fh)
{
char line[ 256 ];
// read the line of text until the end of text
// but not more than array size provided by AmiBroker
while( fgets( line, sizeof( line ), fh ) && iLines < nSize )
{
// get array entry
struct Quotation *qt = &pQuotes[ iLines ];
char* pTmp = NULL;
// parse line contents: divide tokens separated by comma (strtok) and interpret values
// date and time first
int datenum = atoi( strtok_s( line, ",", &pTmp) ); // YYMMDD
int timenum = atoi( strtok_s( NULL, ",", &pTmp) ); // HHMM
// unpack datenum and timenum and store date/time
qt->DateTime.Date = 0; // make sure that date structure is intialized with zero
qt->DateTime.PackDate.Minute = timenum % 100;
qt->DateTime.PackDate.Hour = timenum / 100;
qt->DateTime.PackDate.Year = 2000 + datenum / 10000;
qt->DateTime.PackDate.Month = ( datenum / 100 ) % 100;
qt->DateTime.PackDate.Day = datenum % 100;
// now OHLC price fields
qt->Open = (float) atof( strtok_s( NULL, ",", &pTmp) );
qt->High = (float) atof( strtok_s( NULL, ",", &pTmp) );
qt->Low = (float) atof( strtok_s( NULL, ",", &pTmp) );
qt->Price = (float) atof( strtok_s( NULL, ",", &pTmp) ); // close price
// ... and Volume
qt->Volume = (float) atof( strtok_s( NULL, ",\n", &pTmp) );
iLines++;
}
// close the file once we are done
fclose( fh );
}
// return number of lines read which is equal to
// number of quotes
return iLines;
}

Related

Using .c_str' with pointers (and also pointers to pointers)

so, I encountered a little problem and I am kinda stuck.
Basically I am trying to pass the value of a string** in C-type form to a char* string
The code is as follows:
static int BuildDBListSql( std::string **SqlBuf,
const char* ColumnNames,
const char* TableNames,
const char* CmdText,
sUINT Mode)
{
int rtnval = sSUCCESS;
const char * testSql = ( Mode & 02 ) ? ColumnNames : CmdText;
if ( SU_DbControl::DbCreateTradeTempTables(testSql) != sSUCCESS )
{
sLogMessage("Problem with temporary table results", sLOG_ERROR, 0);
return( sERROR );
}
if ( Mode & 02 )
{
*SqlBuf = new std::string[strlen(ColumnNames) + SQL_MAX_SELECT*40];
*SqlBuf = &std::string(ColumnNames);
if ( !( Mode & 010 ) )
{
// Attach State/Retrieval SQL.
char* SqlBufcopy = (*SqlBuf)->c_str();
sSQLInsertStateAndRetrieval( sDbConvertMode( Mode ), SqlBufcopy);
}
}
// SQL fragments are being passed:
else
{
size_t sqlBufLength = 0;
if ( Mode & 010 )
{
sqlBufLength = strlen(ColumnNames) + strlen(TableNames) + strlen(CmdText) + SQL_MAX_SELECT;
*SqlBuf = new std::string[ sqlBufLength ];
//sprintf( *SqlBuf, "SELECT %s FROM %s %s ",
*SqlBuf = fmt::format("SELECT {} FROM {} {} ", ColumnNames, TableNames, CmdText); // ColumnNames, TableNames, CmdText );
}
else
{
std::string *sqlPtr = new char[strlen(CmdText) + 2*SQL_MAX_SELECT];
strcpy( sqlPtr, CmdText );
sSQLSpecializeWhereClause( TableNames, sqlPtr );
sqlBufLength = strlen(ColumnNames) + strlen(TableNames) + SQL_MAX_SELECT;
sqlBufLength += strchr(TableNames, ',') ? strlen(CmdText) : strlen(sqlPtr);
*SqlBuf = new char[ sqlBufLength ];
sprintf( *SqlBuf, "SELECT %s From %s %s",
ColumnNames,
TableNames,
strchr( TableNames, ',' ) ? CmdText : sqlPtr );
delete [] sqlPtr;
// Attach State/Retrieval SQL
rtnval = sSQLInsertStateAndRetrieval( sDbConvertMode( Mode ),
*SqlBuf );
}
}
if (Mode & 0100)
{
char * tempBuf = sEntitySQLToDbSQL(*SqlBuf);
if( tempBuf )
{
delete [] *SqlBuf;
*SqlBuf = new char[ strlen(tempBuf) + 1];
strcpy(*SqlBuf, tempBuf);
}
else
{
sLogMessage("Error in sEntitySQLToDbSQL", sLOG_ERROR, 0);
return( sERROR );
}
}
return rtnval;
}
i get this error when running the solution: related to this line of code char* SqlBufcopy = (*SqlBuf)->c_str();
left of '.c_str' must have class/struct/union, type is std::string**
I kinda understand that the error is there due to me trying to get a c-type string out of a pointer, but I dont know the correct syntax to do what i want to do.
I tried with
char *SqlBufcopy = *SqlBuf.c_str()
also with
char *SqlBufcopy = *SqlBuf->c_str()
and it didnt work, help pls
To fix the error you ask about, change char *SqlBufcopy = *SqlBuf.c_str(); to
char *SqlBufcopy = (*SqlBuf)->c_str();
Reason: SqlBuf is pointer to pointer (which makes no sense at all), so to get to the actual object, you need to dereference it twice.

Difficulty implementing code 128 C rule

Code related to text encoding:
const char* toCode128C( const char* texto ) {
int tamanhoTexto = strlen( texto );
int tamanhoComando = strlen( "{C" ) + tamanhoTexto;
char* printerCodBarras = new char[ tamanhoComando ];
memcpy( printerCodBarras, "{C", tamanhoComando );
for ( int i = 0; i < tamanhoTexto; i += 2 ) {
int num = QString( texto ).mid( i, 2 ).toInt();
QString vl = QString( static_cast<char>( num ) );
strncat( printerCodBarras, vl.toStdString().c_str(), 1 );
}
return printerCodBarras;
}
Encoding occurs successfully, except when it contains a "00" for example code 59900001, the transformation occurs from two characters to two characters, or error occurs when encoding the value "00", thus making the (00) is not printed.

Weird error on mysql_stmt_execute

I have a weird error when trying to execute mysql_stmt_execute.
The flow goes:
I get the list of the tables in my database I am connecting. (catalog, schema and name)
For every table I'm getting the list of foreign keys, fields and indexes.
Everything goes good until I hit the table named performance_schema.events_stages_summary_by_account_by_event_name.
I get the error: Identifier name "events_stages_summary_by_account_by_event_name" is too long. The weird thing is that the name is not an identifier - it is a parameter to the query and it is less than 64 characters which is the identifier limit.
Below is the relevant code:
std::wstring query3 = L"SELECT kcu.column_name, kcu.ordinal_position, kcu.referenced_table_schema, kcu.referenced_table_name, kcu.referenced_column_name, rc.update_rule, rc.delete_rule FROM information_schema.key_column_usage kcu, information_schema.referential_constraints rc WHERE kcu.constraint_name = rc.constraint_name AND kcu.table_catalog = ? AND kcu.table_schema = ? AND kcu.table_name = ?;";
char *catalog_name = row[0] ? row[0] : NULL;
char *schema_name = row[1] ? row[1] : NULL;
char *table_name = row[2] ? row[2] : NULL;
MYSQL_BIND params[3];
unsigned long str_length1, str_length2, str_length3;
str_length1 = strlen( catalog_name ) * 2;
str_length2 = strlen( schema_name ) * 2;
str_length3 = strlen( table_name ) * 2;
str_data1 = new char[str_length1], str_data2 = new char[str_length2], str_data3 = new char[str_length3];
memset( str_data1, '\0', str_length1 );
memset( str_data2, '\0', str_length2 );
memset( str_data3, '\0', str_length3 );
memset( params, 0, sizeof( params ) );
strncpy( str_data1, catalog_name, str_length1 );
strncpy( str_data2, schema_name, str_length2 );
strncpy( str_data3, table_name, str_length3 );
params[0].buffer_type = MYSQL_TYPE_STRING;
params[0].buffer = (char *) str_data1;
params[0].buffer_length = strlen( str_data1 );
params[0].is_null = 0;
params[0].length = &str_length1;
params[1].buffer_type = MYSQL_TYPE_STRING;
params[1].buffer = (char *) str_data2;
params[1].buffer_length = strlen( str_data2 );
params[1].is_null = 0;
params[1].length = &str_length2;
params[2].buffer_type = MYSQL_TYPE_STRING;
params[2].buffer = (char *) str_data3;
params[2].buffer_length = strlen( str_data3 );
params[2].is_null = 0;
params[2].length = &str_length3;
if( mysql_stmt_bind_param( res1, params ) )
{
std::wstring err = m_pimpl->m_myconv.from_bytes( mysql_stmt_error( res1 ) );
errorMsg.push_back( err );
result = 1;
break;
}
else
{
prepare_meta_result = mysql_stmt_result_metadata( res1 );
if( !prepare_meta_result )
{
std::wstring err = m_pimpl->m_myconv.from_bytes( mysql_stmt_error( res1 ) );
errorMsg.push_back( err );
result = 1;
break;
}
else
{
if( mysql_stmt_execute( res1 ) )
{
std::wstring err = m_pimpl->m_myconv.from_bytes( mysql_stmt_error( res1 ) );
errorMsg.push_back( err );
result = 1;
break;
}
Could someone please shed some light on the error? I can probably try to skip this table but I'd prefer not to.
[EDIT]
mysql --version
mysql ver 14.14 Distrib 5.6.35, for Linux (x86+64) using Editine wrapper
[/EDIT]
Edit:
Seems that the code is indeed OK and the strncpy is OK. I mistakenly read that the allocation was twice the length of the string but the length was still only one length of the string.
The reason why you see that error is because you are using a string which is not null terminated. This is caused by the fact that strncpy does not null-terminate the string if it exceeds the given limit and the limit you use is the actual length of the string:
memset( str_data1, '\0', str_length1 );
strncpy( str_data1, catalog_name, str_length1 );
params[0].buffer_length = strlen( str_data1 );
A better way to do this would be to use either snprintf(3) that does null terminate the string or by using the std::string constructor that takes a const char* and a length as parameters.

libpng error: read error (Visual Studio 2010)

i've been struggling to get libpng to work on my opengl c++ program. I am trying to load png's as textures. I have downloaded the libpng16 source code and built it using Visual Studio 2010. I have correctly linked the lib files and included the png.h file.
When I build my project, libpng prints "libpng error: read error" to my console and nothing else. I have tried all the solutions i've found on the internet including changing my runtime configurations on the libpng project to match my project that im using it on.
The error occurs at the png_read_png function:
FILE * file = fopen(filename,"r");
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING , NULL ,NULL , NULL );
if ( png_ptr == NULL )
{
printf ( "Could not initialize libPNG ’s read struct.\n" ) ;
exit(-1);
}
png_infop png_info_ptr = png_create_info_struct(png_ptr) ;
if ( png_info_ptr == NULL )
{
printf ("Could not initialize libPNG ’s info pointer.\n");
exit ( -1) ;
}
if (setjmp(png_jmpbuf(png_ptr)))
{
printf ( "LibPNG encountered an error.\n" ) ;
png_destroy_read_struct(&png_ptr, &png_info_ptr ,NULL );
exit( -1);
}
png_init_io ( png_ptr , file );
png_read_png ( png_ptr , png_info_ptr , 0 , NULL ) ;
png_uint_32 png_width = 0;
png_uint_32 png_height = 0;
int bits = 0;
int colour_type = 0;
png_get_IHDR ( png_ptr , png_info_ptr , & png_width , & png_height ,& bits , & colour_type ,NULL , NULL , NULL );
const unsigned BITS_PER_BYTE = 8;
unsigned bytes_per_colour = (unsigned)bits/ BITS_PER_BYTE ;
unsigned colours_per_pixel;
if ( colour_type == PNG_COLOR_TYPE_RGB)
{
colours_per_pixel = 3;
}
else
{
printf ( " Colour types other than RGB are not supported." ) ;
exit ( -1) ;
}
printf ( "png_width = %d, png_height = %d , bits = %d, colour type = %d. \n" , png_width , png_height , bits , colour_type );
unsigned char * data = new unsigned char [ png_width * png_height * colours_per_pixel * bytes_per_colour];
png_bytepp row_pointers = png_get_rows ( png_ptr , png_info_ptr ) ;
unsigned index = 0;
for ( unsigned y = 0; y < png_height ; y ++)
{
unsigned x = 0;
while ( x < png_width * colours_per_pixel * bytes_per_colour) {
data [index++] = row_pointers [y][x++];
data [index++] = row_pointers [y][x++];
data [index++] = row_pointers [y][x++];
}
}
I have made sure that the correct filename is passed and I have tried multiple different PNG's
Any assistance with this will be appreciated
Thanks
On Windows you must open image files in binary mode, otherwise any occurance of a sequence of bytes, that could be interpreted as will be converted into a single . Right now you're opening the file in standard mode, which is text mode. You can open in binary mode, by adding a 'b' to the mode string, i.e.
FILE * file = fopen(filename,"rb");

COleSafeArray / VARIANT memory leak?

I want to export a lot of (table) data to Excel. I'm developing on Windows Xp, Vs2005. I'm filling a COleSafeArray, which was initialized like this:
safeArray.Create( VT_VARIANT, 2, numElements ); // 2 dimensional, 30000 rows, 3 columns
Now the filling is really fast, but in TaskManager/Process Explorer/VMMap, it looks like some of the memory does not get released properly (VMMap still finds my dummy strings in the memory). I tried the tips (disabling BSTR caching) from the following pages, but had no success so far:
https://devblogs.microsoft.com/oldnewthing/20091127-00/?p=15883
http://blogs.msdn.com/larryosterman/archive/2004/09/28/235304.aspx
Is there still the caching taking place (I've set the environment variable OANOCACHE = 1), or is there something wrong with my code?
Note: This is part of a MFC dialog based non-unicode application.
//-----------------------------------------------------------------------------
template< typename _ValueType >
void setSafeArrayElement( const _ValueType& value,
const int row,
const int column,
COleSafeArray& safeArray
)
{
VARIANT variant;
VariantInit(&variant);
{
COleVariant oleVariant = value;
variant = oleVariant;
oleVariant.Detach();
}
long coordinates[2] = { row, column };
safeArray.PutElement( coordinates, &variant );
VariantClear(&variant);
}
//-----------------------------------------------------------------------------
#define XL_CELLTYPE_TEXT "#"
#define XL_CELLTYPE_DOUBLE2 "#'##0.00"
#define XL_CELLTYPE_DOUBLE3 "#'##0.000"
#define XL_CELLTYPE_DOUBLE4 "#'##0.0000"
#define XL_CELLTYPE_DOUBLE6 "#'##0.000000"
#define XL_CELLTYPE_DOUBLE8 "#'##0.00000000"
#define XL_CELLTYPE_NUMBER "0"
#define XL_CELLTYPE_NUMBER1000 "#'##0"
#define XL_CELLTYPE_DATE "TT.MM.JJJJ"
#define XL_CELLTYPE_GENERAL "Standard"
//-----------------------------------------------------------------------------
void CexcelTestDlg::OnBnClickedButton2()
{
const bool closeExcel = true;
const int rows = 30000;
const int columns = 3;
//AfxOleGetMessageFilter()->SetMessagePendingDelay( x );
AfxOleGetMessageFilter()->EnableNotRespondingDialog( FALSE );
AfxOleGetMessageFilter()->EnableBusyDialog( FALSE );
Excel11::_ApplicationPtr app;
Excel11::WorkbooksPtr books;
Excel11::_WorkbookPtr book;
Excel11::SheetsPtr sheets;
Excel11::_WorksheetPtr sheet;
app.CreateInstance( "Excel.Application" );
try
{
//app->Visible = VARIANT_TRUE;
app->Visible = VARIANT_FALSE;
app->Interactive = VARIANT_FALSE;
app->UserControl = VARIANT_FALSE;
app->ScreenUpdating = VARIANT_FALSE;
app->DisplayAlerts = VARIANT_FALSE;
books = app->GetWorkbooks(); // all open files
book = books->Add(); // add new file
sheets = book->Sheets; // all worksheets
try
{
COleSafeArray safeArray;
DWORD numElements[] = { rows, columns };
safeArray.Create( VT_VARIANT, 2, numElements );
// rename default worksheet
Excel11::_WorksheetPtr
sheet1 = sheets->GetItem(1);
sheet1->Name = "Blah";
// format columns
{
std::string coords = getExcelCoordinates( 0, 0 ); // getExcelCoordinates returns strings like "A1", "F23", ... (excel cell coordinates)
Excel11::RangePtr range = sheet1->Range[coords.c_str()][coords.c_str()];
range = range->EntireColumn;
range->NumberFormat = XL_CELLTYPE_TEXT;
coords = getExcelCoordinates( 0, 1 );
range = sheet1->Range[coords.c_str()][coords.c_str()];
range = range->EntireColumn;
range->NumberFormat = XL_CELLTYPE_DATE;
coords = getExcelCoordinates( 0, 2 );
range = sheet1->Range[coords.c_str()][coords.c_str()];
range = range->EntireColumn;
range->NumberFormat = XL_CELLTYPE_DOUBLE2;
}
// fill line by line
for( int row = 0; row < rows; ++row )
{
CString rowName;
rowName.Format( "%d", row + 1 );
// Text
CString v0 = CString( "Wusel Dusel " ) + rowName;
setSafeArrayElement( v0, row, 0, safeArray );
// Date
CString v1 = "11.12.1975";
setSafeArrayElement( v1, row, 1, safeArray );
// Number
double v2 = 123.45;
setSafeArrayElement( v2, row, 2, safeArray );
}
// export safearray to excel
if( rows )
{
const std::string cellCoordTopLeft = getExcelCoordinates( 0, 0 );
const std::string cellCoordBottomRight = getExcelCoordinates( rows-1, columns-1 );
Excel11::RangePtr range = sheet1->Range[ cellCoordTopLeft.c_str(), cellCoordBottomRight.c_str()];
COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR);
// export the whole safeArray contents to excel
range->PutValue( vtOptional, COleVariant( safeArray ) );
}
// optimize column widths
Excel11::RangePtr cells = sheet1->Cells;
cells->Select();
cells->EntireColumn->AutoFit();
Excel11::RangePtr singleCell = sheet1->Range["A1"]["A1"];
singleCell->Select();
// clear safeArray
VARIANT* varPtr = 0;
try
{
// Get a pointer to the elements of the array
// and increments the lock count on the array
safeArray.AccessData((LPVOID*)&varPtr);
for( int i = 0; i < rows * columns; ++i )
{
VARIANT& vp = varPtr[i];
VariantClear( &vp );
}
//decrement lock count
safeArray.UnaccessData();
}
catch (COleException *pEx)
{
AfxThrowOleDispatchException(1003, _T("Unexpected Failure in FastSort method"));
pEx->Delete();
}
//safeArray.DestroyData(); //???
//safeArray.DestroyDescriptor(); //???
safeArray.Clear();
}
catch( std::exception& err )
{
MessageBox( err.what() );
}
if( closeExcel )
{
book->Close( VARIANT_FALSE ); // close the file
app->Quit(); // close Excel instance
}
else
{
app->Visible = VARIANT_TRUE;
app->Interactive = VARIANT_TRUE;
app->UserControl = VARIANT_TRUE;
app->ScreenUpdating = VARIANT_TRUE;
app->DisplayAlerts = VARIANT_TRUE;
}
app.Release();
}
catch( _com_error& err )
{
CString s(err.Description().GetBSTR());
MessageBox(s);
}
}